1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/cocoa/window.mm
3 // Purpose: widgets (non tlw) for cocoa
4 // Author: Stefan Csomor
8 // Copyright: (c) Stefan Csomor
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 #include "wx/wxprec.h"
15 #include "wx/dcclient.h"
18 #include "wx/textctrl.h"
19 #include "wx/combobox.h"
23 #include "wx/osx/private.h"
26 #include "wx/evtloop.h"
32 #if wxUSE_DRAG_AND_DROP
37 #include "wx/tooltip.h"
40 #include <objc/objc-runtime.h>
42 // Get the window with the focus
44 NSView* GetViewFromResponder( NSResponder* responder )
47 if ( [responder isKindOfClass:[NSTextView class]] )
49 NSView* delegate = (NSView*) [(NSTextView*)responder delegate];
50 if ( [delegate isKindOfClass:[NSTextField class] ] )
53 view = (NSView*) responder;
57 if ( [responder isKindOfClass:[NSView class]] )
58 view = (NSView*) responder;
63 NSView* GetFocusedViewInWindow( NSWindow* keyWindow )
65 NSView* focusedView = nil;
66 if ( keyWindow != nil )
67 focusedView = GetViewFromResponder([keyWindow firstResponder]);
72 WXWidget wxWidgetImpl::FindFocus()
74 return GetFocusedViewInWindow( [NSApp keyWindow] );;
77 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;
686 if ( fabs(deltaX) > fabs(deltaY) )
688 wxevent.m_wheelAxis = wxMOUSE_WHEEL_HORIZONTAL;
689 wxevent.m_wheelRotation = (int)deltaX;
693 wxevent.m_wheelRotation = (int)deltaY;
699 case NSMouseEntered :
700 wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
703 wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
705 case NSLeftMouseDragged :
706 case NSRightMouseDragged :
707 case NSOtherMouseDragged :
709 wxevent.SetEventType( wxEVT_MOTION ) ;
715 wxevent.m_clickCount = clickCount;
716 wxWindowMac* peer = GetWXPeer();
719 wxevent.SetEventObject(peer);
720 wxevent.SetId(peer->GetId()) ;
724 @implementation wxNSView
728 static BOOL initialized = NO;
732 wxOSXCocoaClassAddWXMethods( self );
736 /* idea taken from webkit sources: overwrite the methods that (private) NSToolTipManager will use to attach its tracking rectangle
737 * then when changing the tooltip send fake view-exit and view-enter methods which will lead to a tooltip refresh
741 - (void)_sendToolTipMouseExited
743 // Nothing matters except window, trackingNumber, and userData.
744 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
745 location:NSMakePoint(0, 0)
748 windowNumber:[[self window] windowNumber]
751 trackingNumber:_lastToolTipTrackTag
752 userData:_lastUserData];
753 [_lastToolTipOwner mouseExited:fakeEvent];
756 - (void)_sendToolTipMouseEntered
758 // Nothing matters except window, trackingNumber, and userData.
759 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
760 location:NSMakePoint(0, 0)
763 windowNumber:[[self window] windowNumber]
766 trackingNumber:_lastToolTipTrackTag
767 userData:_lastUserData];
768 [_lastToolTipOwner mouseEntered:fakeEvent];
771 - (void)setToolTip:(NSString *)string;
777 [self _sendToolTipMouseExited];
780 [super setToolTip:string];
782 [self _sendToolTipMouseEntered];
788 [self _sendToolTipMouseExited];
789 [super setToolTip:nil];
795 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
797 NSTrackingRectTag tag = [super addTrackingRect:rect owner:owner userData:data assumeInside:assumeInside];
800 _lastUserData = data;
801 _lastToolTipOwner = owner;
802 _lastToolTipTrackTag = tag;
807 - (void)removeTrackingRect:(NSTrackingRectTag)tag
809 if (tag == _lastToolTipTrackTag)
811 _lastUserData = NULL;
812 _lastToolTipOwner = nil;
813 _lastToolTipTrackTag = 0;
815 [super removeTrackingRect:tag];
818 #if wxOSX_USE_NATIVE_FLIPPED
825 - (BOOL) canBecomeKeyView
827 wxWidgetCocoaImpl* viewimpl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
828 if ( viewimpl && viewimpl->IsUserPane() && viewimpl->GetWXPeer() )
829 return viewimpl->GetWXPeer()->AcceptsFocus();
839 #if wxUSE_DRAG_AND_DROP
841 // see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
842 // for details on the NSPasteboard -> PasteboardRef conversion
844 NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
846 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
848 return NSDragOperationNone;
850 return impl->draggingEntered(sender, self, _cmd);
853 void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
855 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
859 return impl->draggingExited(sender, self, _cmd);
862 NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
864 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
866 return NSDragOperationNone;
868 return impl->draggingUpdated(sender, self, _cmd);
871 BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
873 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
875 return NSDragOperationNone;
877 return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
882 void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
884 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
888 impl->mouseEvent(event, self, _cmd);
891 void wxOSX_cursorUpdate(NSView* self, SEL _cmd, NSEvent *event)
893 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
897 impl->cursorUpdate(event, self, _cmd);
900 BOOL wxOSX_acceptsFirstMouse(NSView* WXUNUSED(self), SEL WXUNUSED(_cmd), NSEvent *WXUNUSED(event))
902 // This is needed to support click through, otherwise the first click on a window
903 // will not do anything unless it is the active window already.
907 void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
909 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
913 impl->keyEvent(event, self, _cmd);
916 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
918 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
922 impl->insertText(text, self, _cmd);
925 BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
927 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
931 return impl->performKeyEquivalent(event, self, _cmd);
934 BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
936 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
940 return impl->acceptsFirstResponder(self, _cmd);
943 BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
945 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
949 return impl->becomeFirstResponder(self, _cmd);
952 BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
954 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
958 return impl->resignFirstResponder(self, _cmd);
961 #if !wxOSX_USE_NATIVE_FLIPPED
963 BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
965 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
969 return impl->isFlipped(self, _cmd) ? YES:NO;
974 typedef void (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
976 void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
978 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
983 // OS X starts a NSUIHeartBeatThread for animating the default button in a
984 // dialog. This causes a drawRect of the active dialog from outside the
985 // main UI thread. This causes an occasional crash since the wx drawing
986 // objects (like wxPen) are not thread safe.
988 // Notice that NSUIHeartBeatThread seems to be undocumented and doing
989 // [NSWindow setAllowsConcurrentViewDrawing:NO] does not affect it.
990 if ( !wxThread::IsMain() )
992 if ( impl->IsUserPane() )
994 wxWindow* win = impl->GetWXPeer();
995 if ( win->UseBgCol() )
998 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
999 CGContextSaveGState( context );
1001 CGContextSetFillColorWithColor( context, win->GetBackgroundColour().GetCGColor());
1002 CGRect r = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
1003 CGContextFillRect( context, r );
1005 CGContextRestoreGState( context );
1010 // just call the superclass handler, we don't need any custom wx drawing
1011 // here and it seems to work fine:
1012 wxOSX_DrawRectHandlerPtr
1013 superimpl = (wxOSX_DrawRectHandlerPtr)
1014 [[self superclass] instanceMethodForSelector:_cmd];
1015 superimpl(self, _cmd, rect);
1020 #endif // wxUSE_THREADS
1022 return impl->drawRect(&rect, self, _cmd);
1025 void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
1027 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1031 impl->controlAction(self, _cmd, sender);
1034 void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
1036 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1040 impl->controlDoubleAction(self, _cmd, sender);
1043 unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1045 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1046 NSPasteboard *pboard = [sender draggingPasteboard];
1047 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1049 wxWindow* wxpeer = GetWXPeer();
1050 if ( wxpeer == NULL )
1051 return NSDragOperationNone;
1053 wxDropTarget* target = wxpeer->GetDropTarget();
1054 if ( target == NULL )
1055 return NSDragOperationNone;
1057 wxDragResult result = wxDragNone;
1058 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1059 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1061 if ( sourceDragMask & NSDragOperationLink )
1062 result = wxDragLink;
1063 else if ( sourceDragMask & NSDragOperationCopy )
1064 result = wxDragCopy;
1065 else if ( sourceDragMask & NSDragOperationMove )
1066 result = wxDragMove;
1068 PasteboardRef pboardRef;
1069 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1070 target->SetCurrentDragPasteboard(pboardRef);
1071 result = target->OnEnter(pt.x, pt.y, result);
1072 CFRelease(pboardRef);
1074 NSDragOperation nsresult = NSDragOperationNone;
1078 nsresult = NSDragOperationLink;
1080 nsresult = NSDragOperationMove;
1082 nsresult = NSDragOperationCopy;
1089 void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1091 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1092 NSPasteboard *pboard = [sender draggingPasteboard];
1094 wxWindow* wxpeer = GetWXPeer();
1095 if ( wxpeer == NULL )
1098 wxDropTarget* target = wxpeer->GetDropTarget();
1099 if ( target == NULL )
1102 PasteboardRef pboardRef;
1103 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1104 target->SetCurrentDragPasteboard(pboardRef);
1106 CFRelease(pboardRef);
1109 unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1111 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1112 NSPasteboard *pboard = [sender draggingPasteboard];
1113 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1115 wxWindow* wxpeer = GetWXPeer();
1116 if ( wxpeer == NULL )
1117 return NSDragOperationNone;
1119 wxDropTarget* target = wxpeer->GetDropTarget();
1120 if ( target == NULL )
1121 return NSDragOperationNone;
1123 wxDragResult result = wxDragNone;
1124 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1125 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1127 if ( sourceDragMask & NSDragOperationLink )
1128 result = wxDragLink;
1129 else if ( sourceDragMask & NSDragOperationCopy )
1130 result = wxDragCopy;
1131 else if ( sourceDragMask & NSDragOperationMove )
1132 result = wxDragMove;
1134 PasteboardRef pboardRef;
1135 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1136 target->SetCurrentDragPasteboard(pboardRef);
1137 result = target->OnDragOver(pt.x, pt.y, result);
1138 CFRelease(pboardRef);
1140 NSDragOperation nsresult = NSDragOperationNone;
1144 nsresult = NSDragOperationLink;
1146 nsresult = NSDragOperationMove;
1148 nsresult = NSDragOperationCopy;
1155 bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1157 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1159 NSPasteboard *pboard = [sender draggingPasteboard];
1160 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1162 wxWindow* wxpeer = GetWXPeer();
1163 wxDropTarget* target = wxpeer->GetDropTarget();
1164 wxDragResult result = wxDragNone;
1165 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1166 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1168 if ( sourceDragMask & NSDragOperationLink )
1169 result = wxDragLink;
1170 else if ( sourceDragMask & NSDragOperationCopy )
1171 result = wxDragCopy;
1172 else if ( sourceDragMask & NSDragOperationMove )
1173 result = wxDragMove;
1175 PasteboardRef pboardRef;
1176 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1177 target->SetCurrentDragPasteboard(pboardRef);
1179 if (target->OnDrop(pt.x, pt.y))
1180 result = target->OnData(pt.x, pt.y, result);
1182 CFRelease(pboardRef);
1184 return result != wxDragNone;
1187 typedef void (*wxOSX_TextEventHandlerPtr)(NSView* self, SEL _cmd, NSString *event);
1188 typedef void (*wxOSX_EventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
1189 typedef BOOL (*wxOSX_PerformKeyEventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
1190 typedef BOOL (*wxOSX_FocusHandlerPtr)(NSView* self, SEL _cmd);
1192 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1194 // we are getting moved events for all windows in the hierarchy, not something wx expects
1195 // therefore we only handle it for the deepest child in the hierarchy
1196 if ( [event type] == NSMouseMoved )
1198 NSView* hitview = [[[slf window] contentView] hitTest:[event locationInWindow]];
1199 if ( hitview == NULL || hitview != slf)
1203 if ( !DoHandleMouseEvent(event) )
1205 // for plain NSView mouse events would propagate to parents otherwise
1206 // scrollwheel events have to be propagated if not handled in all cases
1207 if (!IsUserPane() || [event type] == NSScrollWheel )
1209 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1210 superimpl(slf, (SEL)_cmd, event);
1212 // super of built-ins keeps the mouse up, as wx expects this event, we have to synthesize it
1213 // only trigger if at this moment the mouse is already up
1214 if ( [ event type] == NSLeftMouseDown && !wxGetMouseState().LeftIsDown() )
1216 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
1217 SetupMouseEvent(wxevent , event) ;
1218 wxevent.SetEventType(wxEVT_LEFT_UP);
1220 GetWXPeer()->HandleWindowEvent(wxevent);
1226 void wxWidgetCocoaImpl::cursorUpdate(WX_NSEvent event, WXWidget slf, void *_cmd)
1228 if ( !SetupCursor(event) )
1230 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1231 superimpl(slf, (SEL)_cmd, event);
1235 bool wxWidgetCocoaImpl::SetupCursor(WX_NSEvent event)
1237 extern wxCursor gGlobalCursor;
1239 if ( gGlobalCursor.IsOk() )
1241 gGlobalCursor.MacInstall();
1246 wxWindow* cursorTarget = GetWXPeer();
1248 SetupCoordinates(x, y, event);
1249 wxPoint cursorPoint( x , y ) ;
1251 while ( cursorTarget && !cursorTarget->MacSetupCursor( cursorPoint ) )
1253 // at least in GTK cursor events are not propagated either ...
1255 cursorTarget = NULL;
1257 cursorTarget = cursorTarget->GetParent() ;
1259 cursorPoint += cursorTarget->GetPosition();
1263 return cursorTarget != NULL;
1267 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1269 if ( [event type] == NSKeyDown )
1271 // there are key equivalents that are not command-combos and therefore not handled by cocoa automatically,
1272 // therefore we call the menubar directly here, exit if the menu is handling the shortcut
1273 if ( [[[NSApplication sharedApplication] mainMenu] performKeyEquivalent:event] )
1276 m_lastKeyDownEvent = event;
1279 if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
1281 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1282 superimpl(slf, (SEL)_cmd, event);
1284 m_lastKeyDownEvent = NULL;
1287 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
1289 if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
1291 wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1292 superimpl(slf, (SEL)_cmd, text);
1297 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
1299 bool handled = false;
1301 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1302 SetupKeyEvent( wxevent, event );
1304 // because performKeyEquivalent is going up the entire view hierarchy, we don't have to
1305 // walk up the ancestors ourselves but let cocoa do it
1307 int command = m_wxPeer->GetAcceleratorTable()->GetCommand( wxevent );
1310 wxEvtHandler * const handler = m_wxPeer->GetEventHandler();
1312 wxCommandEvent command_event( wxEVT_MENU, command );
1313 command_event.SetEventObject( wxevent.GetEventObject() );
1314 handled = handler->ProcessEvent( command_event );
1318 // accelerators can also be used with buttons, try them too
1319 command_event.SetEventType(wxEVT_BUTTON);
1320 handled = handler->ProcessEvent( command_event );
1326 wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1327 return superimpl(slf, (SEL)_cmd, event);
1332 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
1335 return m_wxPeer->AcceptsFocus();
1338 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1339 return superimpl(slf, (SEL)_cmd);
1343 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
1345 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1346 // get the current focus before running becomeFirstResponder
1347 NSView* otherView = FindFocus();
1349 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1350 BOOL r = superimpl(slf, (SEL)_cmd);
1353 DoNotifyFocusEvent( true, otherWindow );
1359 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
1361 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1362 BOOL r = superimpl(slf, (SEL)_cmd);
1364 NSResponder * responder = wxNonOwnedWindowCocoaImpl::GetNextFirstResponder();
1365 NSView* otherView = GetViewFromResponder(responder);
1367 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1369 // NSScrollViews can have their subviews like NSClipView getting focus
1370 // therefore check and use the NSScrollView peer in that case
1371 if ( otherWindow == NULL && [[otherView superview] isKindOfClass:[NSScrollView class]])
1372 otherWindow = FindFromWXWidget([otherView superview]);
1374 // It doesn't make sense to notify about the loss of focus if it's the same
1375 // control in the end, and just a different subview
1376 if ( otherWindow == this )
1379 // NSTextViews have an editor as true responder, therefore the might get the
1380 // resign notification if their editor takes over, don't trigger any event then
1381 if ( r && !m_hasEditor)
1383 DoNotifyFocusEvent( false, otherWindow );
1388 #if !wxOSX_USE_NATIVE_FLIPPED
1390 bool wxWidgetCocoaImpl::isFlipped(WXWidget slf, void *WXUNUSED(_cmd))
1397 #define OSX_DEBUG_DRAWING 0
1399 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
1401 // preparing the update region
1405 // since adding many rects to a region is a costly process, by default use the bounding rect
1407 const NSRect *rects;
1409 [slf getRectsBeingDrawn:&rects count:&count];
1410 for ( int i = 0 ; i < count ; ++i )
1412 updateRgn.Union(wxFromNSRect(slf, rects[i]));
1415 updateRgn.Union(wxFromNSRect(slf,*(NSRect*)rect));
1418 wxWindow* wxpeer = GetWXPeer();
1420 if ( wxpeer->MacGetLeftBorderSize() != 0 || wxpeer->MacGetTopBorderSize() != 0 )
1422 // as this update region is in native window locals we must adapt it to wx window local
1423 updateRgn.Offset( wxpeer->MacGetLeftBorderSize() , wxpeer->MacGetTopBorderSize() );
1426 // Restrict the update region to the shape of the window, if any, and also
1427 // remember the region that we need to clear later.
1428 wxNonOwnedWindow* const tlwParent = wxpeer->MacGetTopLevelWindow();
1429 const bool isTopLevel = tlwParent == wxpeer;
1431 if ( tlwParent->GetWindowStyle() & wxFRAME_SHAPED )
1434 clearRgn = updateRgn;
1436 int xoffset = 0, yoffset = 0;
1437 wxRegion rgn = tlwParent->GetShape();
1438 wxpeer->MacRootWindowToWindow( &xoffset, &yoffset );
1439 rgn.Offset( xoffset, yoffset );
1440 updateRgn.Intersect(rgn);
1444 // Exclude the window shape from the region to be cleared below.
1445 rgn.Xor(wxpeer->GetSize());
1446 clearRgn.Intersect(rgn);
1450 wxpeer->GetUpdateRegion() = updateRgn;
1452 // setting up the drawing context
1454 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1455 CGContextSaveGState( context );
1457 #if OSX_DEBUG_DRAWING
1458 CGContextBeginPath( context );
1459 CGContextMoveToPoint(context, 0, 0);
1460 NSRect bounds = [slf bounds];
1461 CGContextAddLineToPoint(context, 10, 0);
1462 CGContextMoveToPoint(context, 0, 0);
1463 CGContextAddLineToPoint(context, 0, 10);
1464 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1465 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1466 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1467 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1468 CGContextClosePath( context );
1469 CGContextStrokePath(context);
1472 if ( ![slf isFlipped] )
1474 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1475 CGContextScaleCTM( context, 1, -1 );
1478 wxpeer->MacSetCGContextRef( context );
1480 bool handled = wxpeer->MacDoRedraw( 0 );
1481 CGContextRestoreGState( context );
1483 CGContextSaveGState( context );
1487 SEL _cmd = @selector(drawRect:);
1488 wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1489 superimpl(slf, _cmd, *(NSRect*)rect);
1490 CGContextRestoreGState( context );
1491 CGContextSaveGState( context );
1493 // as we called restore above, we have to flip again if necessary
1494 if ( ![slf isFlipped] )
1496 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1497 CGContextScaleCTM( context, 1, -1 );
1502 // We also need to explicitly draw the part of the top level window
1503 // outside of its region with transparent colour to ensure that it is
1504 // really transparent.
1505 if ( clearRgn.IsOk() )
1507 wxMacCGContextStateSaver saveState(context);
1508 wxWindowDC dc(wxpeer);
1509 dc.SetBackground(wxBrush(wxTransparentColour));
1510 dc.SetDeviceClippingRegion(clearRgn);
1514 #if wxUSE_GRAPHICS_CONTEXT
1515 // If the window shape is defined by a path, stroke the path to show
1516 // the window border.
1517 const wxGraphicsPath& path = tlwParent->GetShapePath();
1518 if ( !path.IsNull() )
1520 CGContextSetLineWidth(context, 1);
1521 CGContextSetStrokeColorWithColor(context, wxLIGHT_GREY->GetCGColor());
1522 CGContextAddPath(context, (CGPathRef) path.GetNativePath());
1523 CGContextStrokePath(context);
1525 #endif // wxUSE_GRAPHICS_CONTEXT
1528 wxpeer->MacPaintChildrenBorders();
1529 wxpeer->MacSetCGContextRef( NULL );
1530 CGContextRestoreGState( context );
1533 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1535 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1538 wxpeer->OSXSimulateFocusEvents();
1539 wxpeer->OSXHandleClicked(0);
1543 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1547 void wxWidgetCocoaImpl::controlTextDidChange()
1549 wxWindow* wxpeer = (wxWindow*)GetWXPeer();
1552 // since native rtti doesn't have to be enabled and wx' rtti is not aware of the mixin wxTextEntry, workaround is needed
1553 wxTextCtrl *tc = wxDynamicCast( wxpeer , wxTextCtrl );
1554 wxComboBox *cb = wxDynamicCast( wxpeer , wxComboBox );
1556 tc->SendTextUpdatedEventIfAllowed();
1558 cb->SendTextUpdatedEventIfAllowed();
1561 wxFAIL_MSG("Unexpected class for controlTextDidChange event");
1568 #if OBJC_API_VERSION >= 2
1570 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1571 class_addMethod(c, s, i, t );
1575 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1576 { s, (char*) t, i },
1580 void wxOSXCocoaClassAddWXMethods(Class c)
1583 #if OBJC_API_VERSION < 2
1584 static objc_method wxmethods[] =
1588 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1589 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1590 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1592 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1593 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1594 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1596 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1598 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1599 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1600 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1602 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
1604 wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1605 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1606 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1608 wxOSX_CLASS_ADD_METHOD(c, @selector(cursorUpdate:), (IMP) wxOSX_cursorUpdate, "v@:@" )
1610 wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1611 wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1612 wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1614 wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1616 wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
1618 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1619 wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1620 wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1622 #if !wxOSX_USE_NATIVE_FLIPPED
1623 wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1625 wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1627 wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1628 wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1630 #if wxUSE_DRAG_AND_DROP
1631 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1632 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1633 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1634 wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1637 #if OBJC_API_VERSION < 2
1639 static int method_count = WXSIZEOF( wxmethods );
1640 static objc_method_list *wxmethodlist = NULL;
1641 if ( wxmethodlist == NULL )
1643 wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1644 memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1645 wxmethodlist->method_count = method_count;
1646 wxmethodlist->obsolete = 0;
1648 class_addMethods( c, wxmethodlist );
1653 // C++ implementation class
1656 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1658 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl, bool isUserPane ) :
1659 wxWidgetImpl( peer, isRootControl, isUserPane )
1664 // check if the user wants to create the control initially hidden
1665 if ( !peer->IsShown() )
1666 SetVisibility(false);
1668 // gc aware handling
1670 CFRetain(m_osxView);
1671 [m_osxView release];
1674 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1679 void wxWidgetCocoaImpl::Init()
1682 #if !wxOSX_USE_NATIVE_FLIPPED
1685 m_lastKeyDownEvent = NULL;
1686 m_hasEditor = false;
1689 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1691 RemoveAssociations( this );
1693 if ( !IsRootControl() )
1695 NSView *sv = [m_osxView superview];
1697 [m_osxView removeFromSuperview];
1699 // gc aware handling
1701 CFRelease(m_osxView);
1704 bool wxWidgetCocoaImpl::IsVisible() const
1706 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1709 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1711 [m_osxView setHidden:(visible ? NO:YES)];
1714 // ----------------------------------------------------------------------------
1715 // window animation stuff
1716 // ----------------------------------------------------------------------------
1718 // define a delegate used to refresh the window during animation
1719 @interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
1725 - (id)init:(wxWindow *)win;
1729 // NSAnimationDelegate methods
1730 - (void)animationDidEnd:(NSAnimation*)animation;
1731 - (void)animation:(NSAnimation*)animation
1732 didReachProgressMark:(NSAnimationProgress)progress;
1735 @implementation wxNSAnimationDelegate
1737 - (id)init:(wxWindow *)win
1739 self = [super init];
1752 - (void)animation:(NSAnimation*)animation
1753 didReachProgressMark:(NSAnimationProgress)progress
1755 wxUnusedVar(animation);
1756 wxUnusedVar(progress);
1758 m_win->SendSizeEvent();
1761 - (void)animationDidEnd:(NSAnimation*)animation
1763 wxUnusedVar(animation);
1771 wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1773 wxShowEffect effect,
1776 // create the dictionary describing the animation to perform on this view
1778 viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1779 NSMutableDictionary * const
1780 dict = [NSMutableDictionary dictionaryWithCapacity:4];
1781 [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1783 // determine the start and end rectangles assuming we're hiding the window
1784 const wxRect rectOrig = win->GetRect();
1792 if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1793 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1794 effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1795 else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1796 effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1797 effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1798 else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1799 effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1800 effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1801 else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1802 effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1803 effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1808 case wxSHOW_EFFECT_ROLL_TO_LEFT:
1809 case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1813 case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1814 case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1815 rectEnd.x = rectStart.GetRight();
1819 case wxSHOW_EFFECT_ROLL_TO_TOP:
1820 case wxSHOW_EFFECT_SLIDE_TO_TOP:
1824 case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1825 case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1826 rectEnd.y = rectStart.GetBottom();
1830 case wxSHOW_EFFECT_EXPAND:
1831 rectEnd.x = rectStart.x + rectStart.width / 2;
1832 rectEnd.y = rectStart.y + rectStart.height / 2;
1837 case wxSHOW_EFFECT_BLEND:
1838 [dict setObject:(show ? NSViewAnimationFadeInEffect
1839 : NSViewAnimationFadeOutEffect)
1840 forKey:NSViewAnimationEffectKey];
1843 case wxSHOW_EFFECT_NONE:
1844 case wxSHOW_EFFECT_MAX:
1845 wxFAIL_MSG( "unexpected animation effect" );
1849 wxFAIL_MSG( "unknown animation effect" );
1855 // we need to restore it to the original rectangle instead of making it
1857 wxSwap(rectStart, rectEnd);
1859 // and as the window is currently hidden, we need to show it for the
1860 // animation to be visible at all (but don't restore it at its full
1861 // rectangle as it shouldn't appear immediately)
1862 win->SetSize(rectStart);
1866 NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1867 ? [(NSView *)viewOrWin superview]
1869 const NSRect rStart = wxToNSRect(parentView, rectStart);
1870 const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1872 [dict setObject:[NSValue valueWithRect:rStart]
1873 forKey:NSViewAnimationStartFrameKey];
1874 [dict setObject:[NSValue valueWithRect:rEnd]
1875 forKey:NSViewAnimationEndFrameKey];
1877 // create an animation using the values in the above dictionary
1878 NSViewAnimation * const
1879 anim = [[NSViewAnimation alloc]
1880 initWithViewAnimations:[NSArray arrayWithObject:dict]];
1884 // what is a good default duration? Windows uses 200ms, Web frameworks
1885 // use anything from 250ms to 1s... choose something in the middle
1889 [anim setDuration:timeout/1000.]; // duration is in seconds here
1891 // if the window being animated changes its layout depending on its size
1892 // (which is almost always the case) we need to redo it during animation
1894 // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1895 // controls in wxInfoBar visibly jump around)
1896 const int NUM_LAYOUTS = 20;
1897 for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1898 [anim addProgressMark:f];
1900 wxNSAnimationDelegate * const
1901 animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1902 [anim setDelegate:animDelegate];
1903 [anim startAnimation];
1905 // Cocoa is capable of doing animation asynchronously or even from separate
1906 // thread but wx API doesn't provide any way to be notified about the
1907 // animation end and without this we really must ensure that the window has
1908 // the expected (i.e. the same as if a simple Show() had been used) size
1909 // when we return, so block here until the animation finishes
1911 // notice that because the default animation mode is NSAnimationBlocking,
1912 // no user input events ought to be processed from here
1914 wxEventLoopGuarantor ensureEventLoopExistence;
1915 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1916 while ( ![animDelegate isDone] )
1922 // NSViewAnimation is smart enough to hide the NSView being animated at
1923 // the end but we also must ensure that it's hidden for wx too
1926 // and we must also restore its size because it isn't expected to
1927 // change just because the window was hidden
1928 win->SetSize(rectOrig);
1932 // refresh it once again after the end to ensure that everything is in
1934 win->SendSizeEvent();
1937 [anim setDelegate:nil];
1938 [animDelegate release];
1944 bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
1945 wxShowEffect effect,
1948 return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
1951 /* note that the drawing order between siblings is not defined under 10.4 */
1952 /* only starting from 10.5 the subview order is respected */
1954 /* NSComparisonResult is typedef'd as an enum pre-Leopard but typedef'd as
1955 * NSInteger post-Leopard. Pre-Leopard the Cocoa toolkit expects a function
1956 * returning int and not NSComparisonResult. Post-Leopard the Cocoa toolkit
1957 * expects a function returning the new non-enum NSComparsionResult.
1958 * Hence we create a typedef named CocoaWindowCompareFunctionResult.
1960 #if defined(NSINTEGER_DEFINED)
1961 typedef NSComparisonResult CocoaWindowCompareFunctionResult;
1963 typedef int CocoaWindowCompareFunctionResult;
1966 class CocoaWindowCompareContext
1968 wxDECLARE_NO_COPY_CLASS(CocoaWindowCompareContext);
1970 CocoaWindowCompareContext(); // Not implemented
1971 CocoaWindowCompareContext(NSView *target, NSArray *subviews)
1974 // Cocoa sorts subviews in-place.. make a copy
1975 m_subviews = [subviews copy];
1978 ~CocoaWindowCompareContext()
1979 { // release the copy
1980 [m_subviews release];
1983 { return m_target; }
1986 { return m_subviews; }
1988 /* Helper function that returns the comparison based off of the original ordering */
1989 CocoaWindowCompareFunctionResult CompareUsingOriginalOrdering(id first, id second)
1991 NSUInteger firstI = [m_subviews indexOfObjectIdenticalTo:first];
1992 NSUInteger secondI = [m_subviews indexOfObjectIdenticalTo:second];
1993 // NOTE: If either firstI or secondI is NSNotFound then it will be NSIntegerMax and thus will
1994 // likely compare higher than the other view which is reasonable considering the only way that
1995 // can happen is if the subview was added after our call to subviews but before the call to
1996 // sortSubviewsUsingFunction:context:. Thus we don't bother checking. Particularly because
1997 // that case should never occur anyway because that would imply a multi-threaded GUI call
1998 // which is a big no-no with Cocoa.
2000 // Subviews are ordered from back to front meaning one that is already lower will have an lower index.
2001 NSComparisonResult result = (firstI < secondI)
2002 ? NSOrderedAscending /* -1 */
2003 : (firstI > secondI)
2004 ? NSOrderedDescending /* 1 */
2005 : NSOrderedSame /* 0 */;
2010 /* The subview we are trying to Raise or Lower */
2012 /* A copy of the original array of subviews */
2013 NSArray *m_subviews;
2016 /* Causes Cocoa to raise the target view to the top of the Z-Order by telling the sort function that
2017 * the target view is always higher than every other view. When comparing two views neither of
2018 * which is the target, it returns the correct response based on the original ordering
2020 static CocoaWindowCompareFunctionResult CocoaRaiseWindowCompareFunction(id first, id second, void *ctx)
2022 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
2023 // first should be ordered higher
2024 if(first==compareContext->target())
2025 return NSOrderedDescending;
2026 // second should be ordered higher
2027 if(second==compareContext->target())
2028 return NSOrderedAscending;
2029 return compareContext->CompareUsingOriginalOrdering(first,second);
2032 void wxWidgetCocoaImpl::Raise()
2034 NSView* nsview = m_osxView;
2036 NSView *superview = [nsview superview];
2037 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
2039 [superview sortSubviewsUsingFunction:
2040 CocoaRaiseWindowCompareFunction
2041 context: &compareContext];
2045 /* Causes Cocoa to lower the target view to the bottom of the Z-Order by telling the sort function that
2046 * the target view is always lower than every other view. When comparing two views neither of
2047 * which is the target, it returns the correct response based on the original ordering
2049 static CocoaWindowCompareFunctionResult CocoaLowerWindowCompareFunction(id first, id second, void *ctx)
2051 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
2052 // first should be ordered lower
2053 if(first==compareContext->target())
2054 return NSOrderedAscending;
2055 // second should be ordered lower
2056 if(second==compareContext->target())
2057 return NSOrderedDescending;
2058 return compareContext->CompareUsingOriginalOrdering(first,second);
2061 void wxWidgetCocoaImpl::Lower()
2063 NSView* nsview = m_osxView;
2065 NSView *superview = [nsview superview];
2066 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
2068 [superview sortSubviewsUsingFunction:
2069 CocoaLowerWindowCompareFunction
2070 context: &compareContext];
2073 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
2078 // We should do something like this, but it wasn't working in 10.4.
2079 if (GetNeedsDisplay() )
2083 NSRect r = wxToNSRect( [m_osxView superview], *rect );
2084 NSSize offset = NSMakeSize((float)dx, (float)dy);
2085 [m_osxView scrollRect:r by:offset];
2089 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
2091 wxWindowMac* parent = GetWXPeer()->GetParent();
2092 // under Cocoa we might have a contentView in the wxParent to which we have to
2093 // adjust the coordinates
2094 if (parent && [m_osxView superview] != parent->GetHandle() )
2096 int cx = 0,cy = 0,cw = 0,ch = 0;
2097 if ( parent->GetPeer() )
2099 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2104 [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
2105 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
2106 [m_osxView setFrame:r];
2107 [[m_osxView superview] setNeedsDisplayInRect:r];
2110 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
2112 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
2116 // under Cocoa we might have a contentView in the wxParent to which we have to
2117 // adjust the coordinates
2118 wxWindowMac* parent = GetWXPeer()->GetParent();
2119 if (parent && [m_osxView superview] != parent->GetHandle() )
2121 int cx = 0,cy = 0,cw = 0,ch = 0;
2122 if ( parent->GetPeer() )
2124 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2131 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
2133 NSRect rect = [m_osxView frame];
2134 width = (int)rect.size.width;
2135 height = (int)rect.size.height;
2138 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
2140 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
2142 NSView* cv = [m_osxView contentView];
2144 NSRect bounds = [m_osxView bounds];
2145 NSRect rect = [cv frame];
2147 int y = (int)rect.origin.y;
2148 int x = (int)rect.origin.x;
2149 if ( ![ m_osxView isFlipped ] )
2150 y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
2153 width = (int)rect.size.width;
2154 height = (int)rect.size.height;
2159 GetSize( width, height );
2163 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
2166 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
2168 [m_osxView setNeedsDisplay:YES];
2171 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
2173 return [m_osxView needsDisplay];
2176 bool wxWidgetCocoaImpl::CanFocus() const
2178 return [m_osxView canBecomeKeyView] == YES;
2181 bool wxWidgetCocoaImpl::HasFocus() const
2183 return ( FindFocus() == m_osxView );
2186 bool wxWidgetCocoaImpl::SetFocus()
2191 // TODO remove if no issues arise: should not raise the window, only assign focus
2192 //[[m_osxView window] makeKeyAndOrderFront:nil] ;
2193 [[m_osxView window] makeFirstResponder: m_osxView] ;
2197 void wxWidgetCocoaImpl::SetDropTarget(wxDropTarget* target)
2199 [m_osxView unregisterDraggedTypes];
2201 if ( target == NULL )
2204 wxDataObject* dobj = target->GetDataObject();
2208 CFMutableArrayRef typesarray = CFArrayCreateMutable(kCFAllocatorDefault,0,&kCFTypeArrayCallBacks);
2209 dobj->AddSupportedTypes(typesarray);
2210 NSView* targetView = m_osxView;
2211 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2212 targetView = [(NSScrollView*) m_osxView documentView];
2214 [targetView registerForDraggedTypes:(NSArray*)typesarray];
2215 CFRelease(typesarray);
2219 void wxWidgetCocoaImpl::RemoveFromParent()
2221 [m_osxView removeFromSuperview];
2224 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
2226 NSView* container = parent->GetWXWidget() ;
2227 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
2228 [container addSubview:m_osxView];
2230 if( m_wxPeer->IsFrozen() )
2231 [[m_osxView window] disableFlushWindow];
2234 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
2236 NSView* targetView = m_osxView;
2237 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2238 targetView = [(NSScrollView*) m_osxView documentView];
2240 if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
2242 [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2243 green:(CGFloat) (col.Green() / 255.0)
2244 blue:(CGFloat) (col.Blue() / 255.0)
2245 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2249 bool wxWidgetCocoaImpl::SetBackgroundStyle( wxBackgroundStyle style )
2251 BOOL opaque = ( style == wxBG_STYLE_PAINT );
2253 if ( [m_osxView respondsToSelector:@selector(setOpaque:) ] )
2255 [m_osxView setOpaque: opaque];
2261 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
2263 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
2265 wxCFStringRef cf( title , encoding );
2266 [m_osxView setTitle:cf.AsNSString()];
2268 else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
2270 wxCFStringRef cf( title , encoding );
2271 [m_osxView setStringValue:cf.AsNSString()];
2276 void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
2278 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
2279 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
2280 *pt = wxFromNSPoint( to->GetWXWidget(), p );
2283 wxInt32 wxWidgetCocoaImpl::GetValue() const
2285 return [(NSControl*)m_osxView intValue];
2288 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
2290 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
2292 [m_osxView setIntValue:v];
2294 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
2296 [m_osxView setFloatValue:(double)v];
2298 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
2300 [m_osxView setDoubleValue:(double)v];
2304 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
2306 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
2308 [m_osxView setMinValue:(double)v];
2312 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
2314 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
2316 [m_osxView setMaxValue:(double)v];
2320 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
2322 if ( [m_osxView respondsToSelector:@selector(minValue)] )
2324 return (int)[m_osxView minValue];
2329 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
2331 if ( [m_osxView respondsToSelector:@selector(maxValue)] )
2333 return (int)[m_osxView maxValue];
2338 wxBitmap wxWidgetCocoaImpl::GetBitmap() const
2342 // TODO: how to create a wxBitmap from NSImage?
2344 if ( [m_osxView respondsToSelector:@selector(image:)] )
2345 bmp = [m_osxView image];
2351 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
2353 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
2356 [m_osxView setImage:bitmap.GetNSImage()];
2358 [m_osxView setImage:nil];
2360 [m_osxView setNeedsDisplay:YES];
2364 void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
2366 if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
2368 NSCellImagePosition pos;
2388 wxFAIL_MSG( "invalid image position" );
2392 [m_osxView setImagePosition:pos];
2396 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
2398 // implementation in subclass
2401 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
2403 r->x = r->y = r->width = r->height = 0;
2405 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
2407 NSRect former = [m_osxView frame];
2408 [m_osxView sizeToFit];
2409 NSRect best = [m_osxView frame];
2410 [m_osxView setFrame:former];
2411 r->width = (int)best.size.width;
2412 r->height = (int)best.size.height;
2416 bool wxWidgetCocoaImpl::IsEnabled() const
2418 NSView* targetView = m_osxView;
2419 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2420 targetView = [(NSScrollView*) m_osxView documentView];
2422 if ( [targetView respondsToSelector:@selector(isEnabled) ] )
2423 return [targetView isEnabled];
2427 void wxWidgetCocoaImpl::Enable( bool enable )
2429 NSView* targetView = m_osxView;
2430 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2431 targetView = [(NSScrollView*) m_osxView documentView];
2433 if ( [targetView respondsToSelector:@selector(setEnabled:) ] )
2434 [targetView setEnabled:enable];
2437 void wxWidgetCocoaImpl::PulseGauge()
2441 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
2445 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
2447 NSControlSize size = NSRegularControlSize;
2451 case wxWINDOW_VARIANT_NORMAL :
2452 size = NSRegularControlSize;
2455 case wxWINDOW_VARIANT_SMALL :
2456 size = NSSmallControlSize;
2459 case wxWINDOW_VARIANT_MINI :
2460 size = NSMiniControlSize;
2463 case wxWINDOW_VARIANT_LARGE :
2464 size = NSRegularControlSize;
2468 wxFAIL_MSG(wxT("unexpected window variant"));
2471 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
2472 [m_osxView setControlSize:size];
2473 else if ([m_osxView respondsToSelector:@selector(cell)])
2475 id cell = [(id)m_osxView cell];
2476 if ([cell respondsToSelector:@selector(setControlSize:)])
2477 [cell setControlSize:size];
2480 // we need to propagate this to inner views as well
2481 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2483 NSView* targetView = [(NSScrollView*) m_osxView documentView];
2485 if ( [targetView respondsToSelector:@selector(setControlSize:)] )
2486 [targetView setControlSize:size];
2487 else if ([targetView respondsToSelector:@selector(cell)])
2489 id cell = [(id)targetView cell];
2490 if ([cell respondsToSelector:@selector(setControlSize:)])
2491 [cell setControlSize:size];
2496 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&col, long, bool)
2498 NSView* targetView = m_osxView;
2499 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2500 targetView = [(NSScrollView*) m_osxView documentView];
2502 if ([targetView respondsToSelector:@selector(setFont:)])
2503 [targetView setFont: font.OSXGetNSFont()];
2504 if ([targetView respondsToSelector:@selector(setTextColor:)])
2505 [targetView setTextColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2506 green:(CGFloat) (col.Green() / 255.0)
2507 blue:(CGFloat) (col.Blue() / 255.0)
2508 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2511 void wxWidgetCocoaImpl::SetToolTip(wxToolTip* tooltip)
2515 wxCFStringRef cf( tooltip->GetTip() , m_wxPeer->GetFont().GetEncoding() );
2516 [m_osxView setToolTip: cf.AsNSString()];
2520 [m_osxView setToolTip:nil];
2524 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
2526 WXWidget c = control ? control : (WXWidget) m_osxView;
2527 wxWidgetImpl::Associate( c, this ) ;
2528 if ([c respondsToSelector:@selector(setAction:)])
2531 [c setAction: @selector(controlAction:)];
2532 if ([c respondsToSelector:@selector(setDoubleAction:)])
2534 [c setDoubleAction: @selector(controlDoubleAction:)];
2538 NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingCursorUpdate|NSTrackingMouseMoved|NSTrackingActiveAlways|NSTrackingInVisibleRect;
2539 NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: NSZeroRect options: options owner: m_osxView userInfo: nil];
2540 [m_osxView addTrackingArea: area];
2544 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
2546 wxKeyEvent wxevent(wxEVT_CHAR);
2547 SetupKeyEvent( wxevent, event, text );
2549 return GetWXPeer()->OSXHandleKeyEvent(wxevent);
2552 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
2554 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
2555 SetupKeyEvent( wxevent, event );
2557 // Generate wxEVT_CHAR_HOOK before sending any other events but only when
2558 // the key is pressed, not when it's released (the type of wxevent is
2559 // changed by SetupKeyEvent() so it can be wxEVT_KEY_UP too by now).
2560 if ( wxevent.GetEventType() == wxEVT_KEY_DOWN )
2562 wxKeyEvent eventHook(wxEVT_CHAR_HOOK, wxevent);
2563 if ( GetWXPeer()->OSXHandleKeyEvent(eventHook)
2564 && !eventHook.IsNextEventAllowed() )
2568 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
2570 // this will fire higher level events, like insertText, to help
2571 // us handle EVT_CHAR, etc.
2575 if ( [event type] == NSKeyDown)
2577 long keycode = wxOSXTranslateCocoaKey( event, wxEVT_CHAR );
2579 if ( (keycode > 0 && keycode < WXK_SPACE) || keycode == WXK_DELETE || keycode >= WXK_START )
2581 // eventually we could setup a doCommandBySelector catcher and retransform this into the wx key chars
2582 wxKeyEvent wxevent2(wxevent) ;
2583 wxevent2.SetEventType(wxEVT_CHAR);
2584 SetupKeyEvent( wxevent2, event );
2585 wxevent2.m_keyCode = keycode;
2586 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2588 else if (wxevent.CmdDown())
2590 wxKeyEvent wxevent2(wxevent) ;
2591 wxevent2.SetEventType(wxEVT_CHAR);
2592 SetupKeyEvent( wxevent2, event );
2593 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2597 if ( IsUserPane() && !wxevent.CmdDown() )
2599 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2600 [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
2602 [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
2612 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
2614 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
2615 SetupMouseEvent(wxevent , event) ;
2616 bool result = GetWXPeer()->HandleWindowEvent(wxevent);
2618 (void)SetupCursor(event);
2623 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
2625 wxWindow* thisWindow = GetWXPeer();
2626 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
2628 thisWindow->MacInvalidateBorders();
2631 if ( receivedFocus )
2633 wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
2634 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
2635 thisWindow->HandleWindowEvent(eventFocus);
2638 if ( thisWindow->GetCaret() )
2639 thisWindow->GetCaret()->OnSetFocus();
2642 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
2643 event.SetEventObject(thisWindow);
2645 event.SetWindow(otherWindow->GetWXPeer());
2646 thisWindow->HandleWindowEvent(event) ;
2648 else // !receivedFocus
2651 if ( thisWindow->GetCaret() )
2652 thisWindow->GetCaret()->OnKillFocus();
2655 wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
2657 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
2658 event.SetEventObject(thisWindow);
2660 event.SetWindow(otherWindow->GetWXPeer());
2661 thisWindow->HandleWindowEvent(event) ;
2665 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
2669 NSPoint location = [NSEvent mouseLocation];
2670 location = [[m_osxView window] convertScreenToBase:location];
2671 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
2673 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
2675 [(NSCursor*)cursor.GetHCURSOR() set];
2680 void wxWidgetCocoaImpl::CaptureMouse()
2682 // TODO remove if we don't get into problems with cursor settings
2683 // [[m_osxView window] disableCursorRects];
2686 void wxWidgetCocoaImpl::ReleaseMouse()
2688 // TODO remove if we don't get into problems with cursor settings
2689 // [[m_osxView window] enableCursorRects];
2692 #if !wxOSX_USE_NATIVE_FLIPPED
2694 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
2696 m_isFlipped = flipped;
2701 void wxWidgetCocoaImpl::SetDrawingEnabled(bool enabled)
2705 [[m_osxView window] enableFlushWindow];
2706 [m_osxView setNeedsDisplay:YES];
2710 [[m_osxView window] disableFlushWindow];
2717 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
2718 wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
2719 long WXUNUSED(style), long WXUNUSED(extraStyle))
2721 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
2722 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
2724 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v, false, true );
2728 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
2730 NSWindow* tlw = now->GetWXWindow();
2732 wxWidgetCocoaImpl* c = NULL;
2733 if ( now->IsNativeWindowWrapper() )
2735 NSView* cv = [tlw contentView];
2736 c = new wxWidgetCocoaImpl( now, cv, true );
2739 // increase ref count, because the impl destructor will decrement it again
2741 if ( !now->IsShown() )
2747 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2748 c = new wxWidgetCocoaImpl( now, v, true );
2749 c->InstallEventHandler();
2750 [tlw setContentView:v];