1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/cocoa/window.mm
3 // Purpose: widgets (non tlw) for cocoa
4 // Author: Stefan Csomor
8 // Copyright: (c) Stefan Csomor
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 #include "wx/wxprec.h"
15 #include "wx/dcclient.h"
18 #include "wx/textctrl.h"
19 #include "wx/combobox.h"
23 #include "wx/osx/private.h"
26 #include "wx/evtloop.h"
32 #if wxUSE_DRAG_AND_DROP
37 #include "wx/tooltip.h"
40 #include <objc/objc-runtime.h>
42 // Get the window with the focus
44 NSView* wxOSXGetViewFromResponder( NSResponder* responder )
47 if ( [responder isKindOfClass:[NSTextView class]] )
49 NSView* delegate = (NSView*) [(NSTextView*)responder delegate];
50 if ( [delegate isKindOfClass:[NSTextField class] ] )
53 view = (NSView*) responder;
57 if ( [responder isKindOfClass:[NSView class]] )
58 view = (NSView*) responder;
63 NSView* GetFocusedViewInWindow( NSWindow* keyWindow )
65 NSView* focusedView = nil;
66 if ( keyWindow != nil )
67 focusedView = wxOSXGetViewFromResponder([keyWindow firstResponder]);
72 WXWidget wxWidgetImpl::FindFocus()
74 return GetFocusedViewInWindow( [NSApp keyWindow] );;
77 wxWidgetImpl* wxWidgetImpl::FindBestFromWXWidget(WXWidget control)
79 wxWidgetImpl* impl = FindFromWXWidget(control);
81 // NSScrollViews can have their subviews like NSClipView
82 // therefore check and use the NSScrollView peer in that case
83 if ( impl == NULL && [[control superview] isKindOfClass:[NSScrollView class]])
84 impl = FindFromWXWidget([control superview]);
90 NSRect wxOSXGetFrameForControl( wxWindowMac* window , const wxPoint& pos , const wxSize &size , bool adjustForOrigin )
94 window->MacGetBoundsForControl( pos , size , x , y, w, h , adjustForOrigin ) ;
95 wxRect bounds(x,y,w,h);
96 NSView* sv = (window->GetParent()->GetHandle() );
98 return wxToNSRect( sv, bounds );
101 @interface wxNSView : NSView
104 NSTrackingRectTag _lastToolTipTrackTag;
105 id _lastToolTipOwner;
112 @interface NSView(PossibleMethods)
113 - (void)setTitle:(NSString *)aString;
114 - (void)setStringValue:(NSString *)aString;
115 - (void)setIntValue:(int)anInt;
116 - (void)setFloatValue:(float)aFloat;
117 - (void)setDoubleValue:(double)aDouble;
121 - (void)setMinValue:(double)aDouble;
122 - (void)setMaxValue:(double)aDouble;
127 - (void)setEnabled:(BOOL)flag;
129 - (void)setImage:(NSImage *)image;
130 - (void)setControlSize:(NSControlSize)size;
132 - (void)setFont:(NSFont *)fontObject;
136 - (void)setTarget:(id)anObject;
137 - (void)setAction:(SEL)aSelector;
138 - (void)setDoubleAction:(SEL)aSelector;
139 - (void)setBackgroundColor:(NSColor*)aColor;
140 - (void)setOpaque:(BOOL)opaque;
141 - (void)setTextColor:(NSColor *)color;
142 - (void)setImagePosition:(NSCellImagePosition)aPosition;
145 // The following code is a combination of the code listed here:
146 // http://lists.apple.com/archives/cocoa-dev/2008/Apr/msg01582.html
147 // (which can't be used because KLGetCurrentKeyboardLayout etc aren't 64-bit)
148 // and the code here:
149 // http://inquisitivecocoa.com/category/objective-c/
150 @interface NSEvent (OsGuiUtilsAdditions)
151 - (NSString*) charactersIgnoringModifiersIncludingShift;
154 @implementation NSEvent (OsGuiUtilsAdditions)
155 - (NSString*) charactersIgnoringModifiersIncludingShift {
156 // First try -charactersIgnoringModifiers and look for keys which UCKeyTranslate translates
157 // differently than AppKit.
158 NSString* c = [self charactersIgnoringModifiers];
159 if ([c length] == 1) {
160 unichar codepoint = [c characterAtIndex:0];
161 if ((codepoint >= 0xF700 && codepoint <= 0xF8FF) || codepoint == 0x7F) {
165 // This is not a "special" key, so ask UCKeyTranslate to give us the character with no
166 // modifiers attached. Actually, that's not quite accurate; we attach the Command modifier
167 // which hints the OS to use Latin characters where possible, which is generally what we want.
168 NSString* result = @"";
169 TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
170 CFDataRef uchr = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
171 CFRelease(currentKeyboard);
173 // this can happen for some non-U.S. input methods (eg. Romaji or Hiragana)
176 const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout*)CFDataGetBytePtr(uchr);
177 if (keyboardLayout) {
178 UInt32 deadKeyState = 0;
179 UniCharCount maxStringLength = 255;
180 UniCharCount actualStringLength = 0;
181 UniChar unicodeString[maxStringLength];
183 OSStatus status = UCKeyTranslate(keyboardLayout,
186 cmdKey >> 8, // force the Command key to "on"
188 kUCKeyTranslateNoDeadKeysMask,
195 result = [NSString stringWithCharacters:unicodeString length:(NSInteger)actualStringLength];
201 long wxOSXTranslateCocoaKey( NSEvent* event, int eventType )
205 if ([event type] != NSFlagsChanged)
207 NSString* s = [event charactersIgnoringModifiersIncludingShift];
208 // backspace char reports as delete w/modifiers for some reason
211 if ( eventType == wxEVT_CHAR && ([event modifierFlags] & NSControlKeyMask) && ( [s characterAtIndex:0] >= 'a' && [s characterAtIndex:0] <= 'z' ) )
213 retval = WXK_CONTROL_A + ([s characterAtIndex:0] - 'a');
217 switch ( [s characterAtIndex:0] )
224 case NSUpArrowFunctionKey :
227 case NSDownArrowFunctionKey :
230 case NSLeftArrowFunctionKey :
233 case NSRightArrowFunctionKey :
236 case NSInsertFunctionKey :
239 case NSDeleteFunctionKey :
242 case NSHomeFunctionKey :
245 // case NSBeginFunctionKey :
246 // retval = WXK_BEGIN;
248 case NSEndFunctionKey :
251 case NSPageUpFunctionKey :
254 case NSPageDownFunctionKey :
255 retval = WXK_PAGEDOWN;
257 case NSHelpFunctionKey :
261 int intchar = [s characterAtIndex: 0];
262 if ( intchar >= NSF1FunctionKey && intchar <= NSF24FunctionKey )
263 retval = WXK_F1 + (intchar - NSF1FunctionKey );
264 else if ( intchar > 0 && intchar < 32 )
272 // Some keys don't seem to have constants. The code mimics the approach
273 // taken by WebKit. See:
274 // http://trac.webkit.org/browser/trunk/WebCore/platform/mac/KeyEventMac.mm
275 switch( [event keyCode] )
280 retval = WXK_CONTROL;
284 retval = WXK_CAPITAL;
287 case 56: // Left Shift
288 case 60: // Right Shift
293 case 61: // Right Alt
297 case 59: // Left Ctrl
298 case 62: // Right Ctrl
299 retval = WXK_RAW_CONTROL;
313 // Check for NUMPAD keys. For KEY_UP/DOWN events we need to use the
314 // WXK_NUMPAD constants, but for the CHAR event we want to use the
315 // standard ascii values
316 if ( eventType != wxEVT_CHAR )
318 switch( [event keyCode] )
321 retval = WXK_NUMPAD_DIVIDE;
324 retval = WXK_NUMPAD_MULTIPLY;
327 retval = WXK_NUMPAD_SUBTRACT;
330 retval = WXK_NUMPAD_ADD;
333 retval = WXK_NUMPAD_ENTER;
336 retval = WXK_NUMPAD_DECIMAL;
339 retval = WXK_NUMPAD0;
342 retval = WXK_NUMPAD1;
345 retval = WXK_NUMPAD2;
348 retval = WXK_NUMPAD3;
351 retval = WXK_NUMPAD4;
354 retval = WXK_NUMPAD5;
357 retval = WXK_NUMPAD6;
360 retval = WXK_NUMPAD7;
363 retval = WXK_NUMPAD8;
366 retval = WXK_NUMPAD9;
369 //retval = [event keyCode];
376 void wxWidgetCocoaImpl::SetupKeyEvent(wxKeyEvent &wxevent , NSEvent * nsEvent, NSString* charString)
378 UInt32 modifiers = [nsEvent modifierFlags] ;
379 int eventType = [nsEvent type];
381 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
382 wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
383 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
384 wxevent.m_controlDown = modifiers & NSCommandKeyMask;
386 wxevent.m_rawCode = [nsEvent keyCode];
387 wxevent.m_rawFlags = modifiers;
389 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
392 if ( eventType != NSFlagsChanged )
394 NSString* nschars = [[nsEvent charactersIgnoringModifiersIncludingShift] uppercaseString];
397 // if charString is set, it did not come from key up / key down
398 wxevent.SetEventType( wxEVT_CHAR );
399 chars = wxCFStringRef::AsString(charString);
403 chars = wxCFStringRef::AsString(nschars);
407 int aunichar = chars.Length() > 0 ? chars[0] : 0;
410 if (wxevent.GetEventType() != wxEVT_CHAR)
412 keyval = wxOSXTranslateCocoaKey(nsEvent, wxevent.GetEventType()) ;
416 wxevent.SetEventType( wxEVT_KEY_DOWN ) ;
419 wxevent.SetEventType( wxEVT_KEY_UP ) ;
421 case NSFlagsChanged :
425 wxevent.SetEventType( wxevent.m_controlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
428 wxevent.SetEventType( wxevent.m_shiftDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
431 wxevent.SetEventType( wxevent.m_altDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
433 case WXK_RAW_CONTROL:
434 wxevent.SetEventType( wxevent.m_rawControlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
445 if ( wxevent.GetEventType() == wxEVT_KEY_UP || wxevent.GetEventType() == wxEVT_KEY_DOWN )
446 keyval = wxToupper( aunichar ) ;
452 // OS X generates events with key codes in Unicode private use area for
453 // unprintable symbols such as cursor arrows (WXK_UP is mapped to U+F700)
454 // and function keys (WXK_F2 is U+F705). We don't want to use them as the
455 // result of wxKeyEvent::GetUnicodeKey() however as it's supposed to return
456 // WXK_NONE for "non characters" so explicitly exclude them.
458 // We only exclude the private use area inside the Basic Multilingual Plane
459 // as key codes beyond it don't seem to be currently used.
460 if ( !(aunichar >= 0xe000 && aunichar < 0xf900) )
461 wxevent.m_uniChar = aunichar;
463 wxevent.m_keyCode = keyval;
465 wxWindowMac* peer = GetWXPeer();
468 wxevent.SetEventObject(peer);
469 wxevent.SetId(peer->GetId()) ;
473 UInt32 g_lastButton = 0 ;
474 bool g_lastButtonWasFakeRight = false ;
476 // better scroll wheel support
477 // see http://lists.apple.com/archives/cocoa-dev/2007/Feb/msg00050.html
479 @interface NSEvent (DeviceDelta)
480 - (CGFloat)deviceDeltaX;
481 - (CGFloat)deviceDeltaY;
484 - (BOOL)hasPreciseScrollingDeltas;
485 - (CGFloat)scrollingDeltaX;
486 - (CGFloat)scrollingDeltaY;
489 void wxWidgetCocoaImpl::SetupCoordinates(wxCoord &x, wxCoord &y, NSEvent* nsEvent)
491 NSPoint locationInWindow = [nsEvent locationInWindow];
493 // adjust coordinates for the window of the target view
494 if ( [nsEvent window] != [m_osxView window] )
496 if ( [nsEvent window] != nil )
497 locationInWindow = [[nsEvent window] convertBaseToScreen:locationInWindow];
499 if ( [m_osxView window] != nil )
500 locationInWindow = [[m_osxView window] convertScreenToBase:locationInWindow];
503 NSPoint locationInView = [m_osxView convertPoint:locationInWindow fromView:nil];
504 wxPoint locationInViewWX = wxFromNSPoint( m_osxView, locationInView );
506 x = locationInViewWX.x;
507 y = locationInViewWX.y;
511 void wxWidgetCocoaImpl::SetupMouseEvent( wxMouseEvent &wxevent , NSEvent * nsEvent )
513 int eventType = [nsEvent type];
514 UInt32 modifiers = [nsEvent modifierFlags] ;
516 SetupCoordinates(wxevent.m_x, wxevent.m_y, nsEvent);
518 // these parameters are not given for all events
519 UInt32 button = [nsEvent buttonNumber];
520 UInt32 clickCount = 0;
522 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
523 wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
524 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
525 wxevent.m_controlDown = modifiers & NSCommandKeyMask;
526 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
528 UInt32 mouseChord = 0;
532 case NSLeftMouseDown :
533 case NSLeftMouseDragged :
536 case NSRightMouseDown :
537 case NSRightMouseDragged :
540 case NSOtherMouseDown :
541 case NSOtherMouseDragged :
546 // a control click is interpreted as a right click
547 bool thisButtonIsFakeRight = false ;
548 if ( button == 0 && (modifiers & NSControlKeyMask) )
551 thisButtonIsFakeRight = true ;
554 // otherwise we report double clicks by connecting a left click with a ctrl-left click
555 if ( clickCount > 1 && button != g_lastButton )
558 // we must make sure that our synthetic 'right' button corresponds in
559 // mouse down, moved and mouse up, and does not deliver a right down and left up
562 case NSLeftMouseDown :
563 case NSRightMouseDown :
564 case NSOtherMouseDown :
565 g_lastButton = button ;
566 g_lastButtonWasFakeRight = thisButtonIsFakeRight ;
573 g_lastButtonWasFakeRight = false ;
575 else if ( g_lastButton == 1 && g_lastButtonWasFakeRight )
576 button = g_lastButton ;
578 // Adjust the chord mask to remove the primary button and add the
579 // secondary button. It is possible that the secondary button is
580 // already pressed, e.g. on a mouse connected to a laptop, but this
581 // possibility is ignored here:
582 if( thisButtonIsFakeRight && ( mouseChord & 1U ) )
583 mouseChord = ((mouseChord & ~1U) | 2U);
586 wxevent.m_leftDown = true ;
588 wxevent.m_rightDown = true ;
590 wxevent.m_middleDown = true ;
592 // translate into wx types
595 case NSLeftMouseDown :
596 case NSRightMouseDown :
597 case NSOtherMouseDown :
598 clickCount = [nsEvent clickCount];
602 wxevent.SetEventType( clickCount > 1 ? wxEVT_LEFT_DCLICK : wxEVT_LEFT_DOWN ) ;
606 wxevent.SetEventType( clickCount > 1 ? wxEVT_RIGHT_DCLICK : wxEVT_RIGHT_DOWN ) ;
610 wxevent.SetEventType( clickCount > 1 ? wxEVT_MIDDLE_DCLICK : wxEVT_MIDDLE_DOWN ) ;
619 case NSRightMouseUp :
620 case NSOtherMouseUp :
621 clickCount = [nsEvent clickCount];
625 wxevent.SetEventType( wxEVT_LEFT_UP ) ;
629 wxevent.SetEventType( wxEVT_RIGHT_UP ) ;
633 wxevent.SetEventType( wxEVT_MIDDLE_UP ) ;
646 wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ;
648 if ( UMAGetSystemVersion() >= 0x1070 )
650 if ( [nsEvent hasPreciseScrollingDeltas] )
652 deltaX = [nsEvent scrollingDeltaX];
653 deltaY = [nsEvent scrollingDeltaY];
657 deltaX = [nsEvent scrollingDeltaX] * 10;
658 deltaY = [nsEvent scrollingDeltaY] * 10;
663 const EventRef cEvent = (EventRef) [nsEvent eventRef];
664 // see http://developer.apple.com/qa/qa2005/qa1453.html
665 // for more details on why we have to look for the exact type
667 bool isMouseScrollEvent = false;
669 isMouseScrollEvent = ::GetEventKind(cEvent) == kEventMouseScroll;
671 if ( isMouseScrollEvent )
673 deltaX = [nsEvent deviceDeltaX];
674 deltaY = [nsEvent deviceDeltaY];
678 deltaX = ([nsEvent deltaX] * 10);
679 deltaY = ([nsEvent deltaY] * 10);
683 wxevent.m_wheelDelta = 10;
684 wxevent.m_linesPerAction = 1;
685 wxevent.m_columnsPerAction = 1;
687 if ( fabs(deltaX) > fabs(deltaY) )
689 wxevent.m_wheelAxis = wxMOUSE_WHEEL_HORIZONTAL;
690 wxevent.m_wheelRotation = (int)deltaX;
694 wxevent.m_wheelRotation = (int)deltaY;
700 case NSMouseEntered :
701 wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
704 wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
706 case NSLeftMouseDragged :
707 case NSRightMouseDragged :
708 case NSOtherMouseDragged :
710 wxevent.SetEventType( wxEVT_MOTION ) ;
716 wxevent.m_clickCount = clickCount;
717 wxWindowMac* peer = GetWXPeer();
720 wxevent.SetEventObject(peer);
721 wxevent.SetId(peer->GetId()) ;
725 @implementation wxNSView
729 static BOOL initialized = NO;
733 wxOSXCocoaClassAddWXMethods( self );
737 /* idea taken from webkit sources: overwrite the methods that (private) NSToolTipManager will use to attach its tracking rectangle
738 * then when changing the tooltip send fake view-exit and view-enter methods which will lead to a tooltip refresh
742 - (void)_sendToolTipMouseExited
744 // Nothing matters except window, trackingNumber, and userData.
745 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
746 location:NSMakePoint(0, 0)
749 windowNumber:[[self window] windowNumber]
752 trackingNumber:_lastToolTipTrackTag
753 userData:_lastUserData];
754 [_lastToolTipOwner mouseExited:fakeEvent];
757 - (void)_sendToolTipMouseEntered
759 // Nothing matters except window, trackingNumber, and userData.
760 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
761 location:NSMakePoint(0, 0)
764 windowNumber:[[self window] windowNumber]
767 trackingNumber:_lastToolTipTrackTag
768 userData:_lastUserData];
769 [_lastToolTipOwner mouseEntered:fakeEvent];
772 - (void)setToolTip:(NSString *)string;
778 [self _sendToolTipMouseExited];
781 [super setToolTip:string];
783 [self _sendToolTipMouseEntered];
789 [self _sendToolTipMouseExited];
790 [super setToolTip:nil];
796 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
798 NSTrackingRectTag tag = [super addTrackingRect:rect owner:owner userData:data assumeInside:assumeInside];
801 _lastUserData = data;
802 _lastToolTipOwner = owner;
803 _lastToolTipTrackTag = tag;
808 - (void)removeTrackingRect:(NSTrackingRectTag)tag
810 if (tag == _lastToolTipTrackTag)
812 _lastUserData = NULL;
813 _lastToolTipOwner = nil;
814 _lastToolTipTrackTag = 0;
816 [super removeTrackingRect:tag];
819 #if wxOSX_USE_NATIVE_FLIPPED
826 - (BOOL) canBecomeKeyView
828 wxWidgetCocoaImpl* viewimpl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
829 if ( viewimpl && viewimpl->IsUserPane() && viewimpl->GetWXPeer() )
830 return viewimpl->GetWXPeer()->AcceptsFocus();
840 #if wxUSE_DRAG_AND_DROP
842 // see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
843 // for details on the NSPasteboard -> PasteboardRef conversion
845 NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
847 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
849 return NSDragOperationNone;
851 return impl->draggingEntered(sender, self, _cmd);
854 void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
856 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
860 return impl->draggingExited(sender, self, _cmd);
863 NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
865 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
867 return NSDragOperationNone;
869 return impl->draggingUpdated(sender, self, _cmd);
872 BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
874 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
876 return NSDragOperationNone;
878 return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
883 void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
885 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
889 impl->mouseEvent(event, self, _cmd);
892 void wxOSX_cursorUpdate(NSView* self, SEL _cmd, NSEvent *event)
894 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
898 impl->cursorUpdate(event, self, _cmd);
901 BOOL wxOSX_acceptsFirstMouse(NSView* WXUNUSED(self), SEL WXUNUSED(_cmd), NSEvent *WXUNUSED(event))
903 // This is needed to support click through, otherwise the first click on a window
904 // will not do anything unless it is the active window already.
908 void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
910 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
914 impl->keyEvent(event, self, _cmd);
917 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
919 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
923 impl->insertText(text, self, _cmd);
926 BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
928 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
932 return impl->performKeyEquivalent(event, self, _cmd);
935 BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
937 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
941 return impl->acceptsFirstResponder(self, _cmd);
944 BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
946 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
950 return impl->becomeFirstResponder(self, _cmd);
953 BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
955 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
959 return impl->resignFirstResponder(self, _cmd);
962 #if !wxOSX_USE_NATIVE_FLIPPED
964 BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
966 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
970 return impl->isFlipped(self, _cmd) ? YES:NO;
975 typedef void (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
977 void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
979 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
984 // OS X starts a NSUIHeartBeatThread for animating the default button in a
985 // dialog. This causes a drawRect of the active dialog from outside the
986 // main UI thread. This causes an occasional crash since the wx drawing
987 // objects (like wxPen) are not thread safe.
989 // Notice that NSUIHeartBeatThread seems to be undocumented and doing
990 // [NSWindow setAllowsConcurrentViewDrawing:NO] does not affect it.
991 if ( !wxThread::IsMain() )
993 if ( impl->IsUserPane() )
995 wxWindow* win = impl->GetWXPeer();
996 if ( win->UseBgCol() )
999 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1000 CGContextSaveGState( context );
1002 CGContextSetFillColorWithColor( context, win->GetBackgroundColour().GetCGColor());
1003 CGRect r = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
1004 CGContextFillRect( context, r );
1006 CGContextRestoreGState( context );
1011 // just call the superclass handler, we don't need any custom wx drawing
1012 // here and it seems to work fine:
1013 wxOSX_DrawRectHandlerPtr
1014 superimpl = (wxOSX_DrawRectHandlerPtr)
1015 [[self superclass] instanceMethodForSelector:_cmd];
1016 superimpl(self, _cmd, rect);
1021 #endif // wxUSE_THREADS
1023 return impl->drawRect(&rect, self, _cmd);
1026 void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
1028 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1032 impl->controlAction(self, _cmd, sender);
1035 void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
1037 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
1041 impl->controlDoubleAction(self, _cmd, sender);
1044 unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1046 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1047 NSPasteboard *pboard = [sender draggingPasteboard];
1048 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1050 wxWindow* wxpeer = GetWXPeer();
1051 if ( wxpeer == NULL )
1052 return NSDragOperationNone;
1054 wxDropTarget* target = wxpeer->GetDropTarget();
1055 if ( target == NULL )
1056 return NSDragOperationNone;
1058 wxDragResult result = wxDragNone;
1059 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1060 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1062 if ( sourceDragMask & NSDragOperationLink )
1063 result = wxDragLink;
1064 else if ( sourceDragMask & NSDragOperationCopy )
1065 result = wxDragCopy;
1066 else if ( sourceDragMask & NSDragOperationMove )
1067 result = wxDragMove;
1069 PasteboardRef pboardRef;
1070 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1071 target->SetCurrentDragPasteboard(pboardRef);
1072 result = target->OnEnter(pt.x, pt.y, result);
1073 CFRelease(pboardRef);
1075 NSDragOperation nsresult = NSDragOperationNone;
1079 nsresult = NSDragOperationLink;
1081 nsresult = NSDragOperationMove;
1083 nsresult = NSDragOperationCopy;
1090 void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1092 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1093 NSPasteboard *pboard = [sender draggingPasteboard];
1095 wxWindow* wxpeer = GetWXPeer();
1096 if ( wxpeer == NULL )
1099 wxDropTarget* target = wxpeer->GetDropTarget();
1100 if ( target == NULL )
1103 PasteboardRef pboardRef;
1104 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1105 target->SetCurrentDragPasteboard(pboardRef);
1107 CFRelease(pboardRef);
1110 unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1112 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1113 NSPasteboard *pboard = [sender draggingPasteboard];
1114 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1116 wxWindow* wxpeer = GetWXPeer();
1117 if ( wxpeer == NULL )
1118 return NSDragOperationNone;
1120 wxDropTarget* target = wxpeer->GetDropTarget();
1121 if ( target == NULL )
1122 return NSDragOperationNone;
1124 wxDragResult result = wxDragNone;
1125 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1126 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1128 if ( sourceDragMask & NSDragOperationLink )
1129 result = wxDragLink;
1130 else if ( sourceDragMask & NSDragOperationCopy )
1131 result = wxDragCopy;
1132 else if ( sourceDragMask & NSDragOperationMove )
1133 result = wxDragMove;
1135 PasteboardRef pboardRef;
1136 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1137 target->SetCurrentDragPasteboard(pboardRef);
1138 result = target->OnDragOver(pt.x, pt.y, result);
1139 CFRelease(pboardRef);
1141 NSDragOperation nsresult = NSDragOperationNone;
1145 nsresult = NSDragOperationLink;
1147 nsresult = NSDragOperationMove;
1149 nsresult = NSDragOperationCopy;
1156 bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1158 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1160 NSPasteboard *pboard = [sender draggingPasteboard];
1161 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1163 wxWindow* wxpeer = GetWXPeer();
1164 wxDropTarget* target = wxpeer->GetDropTarget();
1165 wxDragResult result = wxDragNone;
1166 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1167 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1169 if ( sourceDragMask & NSDragOperationLink )
1170 result = wxDragLink;
1171 else if ( sourceDragMask & NSDragOperationCopy )
1172 result = wxDragCopy;
1173 else if ( sourceDragMask & NSDragOperationMove )
1174 result = wxDragMove;
1176 PasteboardRef pboardRef;
1177 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1178 target->SetCurrentDragPasteboard(pboardRef);
1180 if (target->OnDrop(pt.x, pt.y))
1181 result = target->OnData(pt.x, pt.y, result);
1183 CFRelease(pboardRef);
1185 return result != wxDragNone;
1188 typedef void (*wxOSX_TextEventHandlerPtr)(NSView* self, SEL _cmd, NSString *event);
1189 typedef void (*wxOSX_EventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
1190 typedef BOOL (*wxOSX_PerformKeyEventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
1191 typedef BOOL (*wxOSX_FocusHandlerPtr)(NSView* self, SEL _cmd);
1193 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1195 // we are getting moved events for all windows in the hierarchy, not something wx expects
1196 // therefore we only handle it for the deepest child in the hierarchy
1197 if ( [event type] == NSMouseMoved )
1199 NSView* hitview = [[[slf window] contentView] hitTest:[event locationInWindow]];
1200 if ( hitview == NULL || hitview != slf)
1204 if ( !DoHandleMouseEvent(event) )
1206 // for plain NSView mouse events would propagate to parents otherwise
1207 // scrollwheel events have to be propagated if not handled in all cases
1208 if (!IsUserPane() || [event type] == NSScrollWheel )
1210 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1211 superimpl(slf, (SEL)_cmd, event);
1213 // super of built-ins keeps the mouse up, as wx expects this event, we have to synthesize it
1214 // only trigger if at this moment the mouse is already up
1215 if ( [ event type] == NSLeftMouseDown && !wxGetMouseState().LeftIsDown() )
1217 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
1218 SetupMouseEvent(wxevent , event) ;
1219 wxevent.SetEventType(wxEVT_LEFT_UP);
1221 GetWXPeer()->HandleWindowEvent(wxevent);
1227 void wxWidgetCocoaImpl::cursorUpdate(WX_NSEvent event, WXWidget slf, void *_cmd)
1229 if ( !SetupCursor(event) )
1231 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1232 superimpl(slf, (SEL)_cmd, event);
1236 bool wxWidgetCocoaImpl::SetupCursor(WX_NSEvent event)
1238 extern wxCursor gGlobalCursor;
1240 if ( gGlobalCursor.IsOk() )
1242 gGlobalCursor.MacInstall();
1247 wxWindow* cursorTarget = GetWXPeer();
1249 SetupCoordinates(x, y, event);
1250 wxPoint cursorPoint( x , y ) ;
1252 while ( cursorTarget && !cursorTarget->MacSetupCursor( cursorPoint ) )
1254 // at least in GTK cursor events are not propagated either ...
1256 cursorTarget = NULL;
1258 cursorTarget = cursorTarget->GetParent() ;
1260 cursorPoint += cursorTarget->GetPosition();
1264 return cursorTarget != NULL;
1268 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1270 if ( [event type] == NSKeyDown )
1272 // there are key equivalents that are not command-combos and therefore not handled by cocoa automatically,
1273 // therefore we call the menubar directly here, exit if the menu is handling the shortcut
1274 if ( [[[NSApplication sharedApplication] mainMenu] performKeyEquivalent:event] )
1277 m_lastKeyDownEvent = event;
1280 if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
1282 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1283 superimpl(slf, (SEL)_cmd, event);
1285 m_lastKeyDownEvent = NULL;
1288 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
1290 if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
1292 wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1293 superimpl(slf, (SEL)_cmd, text);
1298 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
1300 bool handled = false;
1302 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1303 SetupKeyEvent( wxevent, event );
1305 // because performKeyEquivalent is going up the entire view hierarchy, we don't have to
1306 // walk up the ancestors ourselves but let cocoa do it
1308 int command = m_wxPeer->GetAcceleratorTable()->GetCommand( wxevent );
1311 wxEvtHandler * const handler = m_wxPeer->GetEventHandler();
1313 wxCommandEvent command_event( wxEVT_MENU, command );
1314 command_event.SetEventObject( wxevent.GetEventObject() );
1315 handled = handler->ProcessEvent( command_event );
1319 // accelerators can also be used with buttons, try them too
1320 command_event.SetEventType(wxEVT_BUTTON);
1321 handled = handler->ProcessEvent( command_event );
1327 wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1328 return superimpl(slf, (SEL)_cmd, event);
1333 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
1336 return m_wxPeer->AcceptsFocus();
1339 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1340 return superimpl(slf, (SEL)_cmd);
1344 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
1346 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1347 // get the current focus before running becomeFirstResponder
1348 NSView* otherView = FindFocus();
1350 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1351 BOOL r = superimpl(slf, (SEL)_cmd);
1354 DoNotifyFocusEvent( true, otherWindow );
1360 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
1362 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1363 BOOL r = superimpl(slf, (SEL)_cmd);
1365 NSResponder * responder = wxNonOwnedWindowCocoaImpl::GetNextFirstResponder();
1366 NSView* otherView = wxOSXGetViewFromResponder(responder);
1368 wxWidgetImpl* otherWindow = FindBestFromWXWidget(otherView);
1370 // It doesn't make sense to notify about the loss of focus if it's the same
1371 // control in the end, and just a different subview
1372 if ( otherWindow == this )
1375 // NSTextViews have an editor as true responder, therefore the might get the
1376 // resign notification if their editor takes over, don't trigger any event then
1377 if ( r && !m_hasEditor)
1379 DoNotifyFocusEvent( false, otherWindow );
1384 #if !wxOSX_USE_NATIVE_FLIPPED
1386 bool wxWidgetCocoaImpl::isFlipped(WXWidget slf, void *WXUNUSED(_cmd))
1393 #define OSX_DEBUG_DRAWING 0
1395 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
1397 // preparing the update region
1401 // since adding many rects to a region is a costly process, by default use the bounding rect
1403 const NSRect *rects;
1405 [slf getRectsBeingDrawn:&rects count:&count];
1406 for ( int i = 0 ; i < count ; ++i )
1408 updateRgn.Union(wxFromNSRect(slf, rects[i]));
1411 updateRgn.Union(wxFromNSRect(slf,*(NSRect*)rect));
1414 wxWindow* wxpeer = GetWXPeer();
1416 if ( wxpeer->MacGetLeftBorderSize() != 0 || wxpeer->MacGetTopBorderSize() != 0 )
1418 // as this update region is in native window locals we must adapt it to wx window local
1419 updateRgn.Offset( wxpeer->MacGetLeftBorderSize() , wxpeer->MacGetTopBorderSize() );
1422 // Restrict the update region to the shape of the window, if any, and also
1423 // remember the region that we need to clear later.
1424 wxNonOwnedWindow* const tlwParent = wxpeer->MacGetTopLevelWindow();
1425 const bool isTopLevel = tlwParent == wxpeer;
1427 if ( tlwParent->GetWindowStyle() & wxFRAME_SHAPED )
1430 clearRgn = updateRgn;
1432 int xoffset = 0, yoffset = 0;
1433 wxRegion rgn = tlwParent->GetShape();
1434 wxpeer->MacRootWindowToWindow( &xoffset, &yoffset );
1435 rgn.Offset( xoffset, yoffset );
1436 updateRgn.Intersect(rgn);
1440 // Exclude the window shape from the region to be cleared below.
1441 rgn.Xor(wxpeer->GetSize());
1442 clearRgn.Intersect(rgn);
1446 wxpeer->GetUpdateRegion() = updateRgn;
1448 // setting up the drawing context
1450 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1451 CGContextSaveGState( context );
1453 #if OSX_DEBUG_DRAWING
1454 CGContextBeginPath( context );
1455 CGContextMoveToPoint(context, 0, 0);
1456 NSRect bounds = [slf bounds];
1457 CGContextAddLineToPoint(context, 10, 0);
1458 CGContextMoveToPoint(context, 0, 0);
1459 CGContextAddLineToPoint(context, 0, 10);
1460 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1461 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1462 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1463 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1464 CGContextClosePath( context );
1465 CGContextStrokePath(context);
1468 if ( ![slf isFlipped] )
1470 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1471 CGContextScaleCTM( context, 1, -1 );
1474 wxpeer->MacSetCGContextRef( context );
1476 bool handled = wxpeer->MacDoRedraw( 0 );
1477 CGContextRestoreGState( context );
1479 CGContextSaveGState( context );
1483 SEL _cmd = @selector(drawRect:);
1484 wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1485 superimpl(slf, _cmd, *(NSRect*)rect);
1486 CGContextRestoreGState( context );
1487 CGContextSaveGState( context );
1489 // as we called restore above, we have to flip again if necessary
1490 if ( ![slf isFlipped] )
1492 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1493 CGContextScaleCTM( context, 1, -1 );
1498 // We also need to explicitly draw the part of the top level window
1499 // outside of its region with transparent colour to ensure that it is
1500 // really transparent.
1501 if ( clearRgn.IsOk() )
1503 wxMacCGContextStateSaver saveState(context);
1504 wxWindowDC dc(wxpeer);
1505 dc.SetBackground(wxBrush(wxTransparentColour));
1506 dc.SetDeviceClippingRegion(clearRgn);
1510 #if wxUSE_GRAPHICS_CONTEXT
1511 // If the window shape is defined by a path, stroke the path to show
1512 // the window border.
1513 const wxGraphicsPath& path = tlwParent->GetShapePath();
1514 if ( !path.IsNull() )
1516 CGContextSetLineWidth(context, 1);
1517 CGContextSetStrokeColorWithColor(context, wxLIGHT_GREY->GetCGColor());
1518 CGContextAddPath(context, (CGPathRef) path.GetNativePath());
1519 CGContextStrokePath(context);
1521 #endif // wxUSE_GRAPHICS_CONTEXT
1524 wxpeer->MacPaintChildrenBorders();
1525 wxpeer->MacSetCGContextRef( NULL );
1526 CGContextRestoreGState( context );
1529 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1531 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1534 wxpeer->OSXSimulateFocusEvents();
1535 wxpeer->OSXHandleClicked(0);
1539 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1543 void wxWidgetCocoaImpl::controlTextDidChange()
1545 wxWindow* wxpeer = (wxWindow*)GetWXPeer();
1548 // since native rtti doesn't have to be enabled and wx' rtti is not aware of the mixin wxTextEntry, workaround is needed
1549 wxTextCtrl *tc = wxDynamicCast( wxpeer , wxTextCtrl );
1550 wxComboBox *cb = wxDynamicCast( wxpeer , wxComboBox );
1552 tc->SendTextUpdatedEventIfAllowed();
1554 cb->SendTextUpdatedEventIfAllowed();
1557 wxFAIL_MSG("Unexpected class for controlTextDidChange event");
1564 #if OBJC_API_VERSION >= 2
1566 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1567 class_addMethod(c, s, i, t );
1571 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1572 { s, (char*) t, i },
1576 void wxOSXCocoaClassAddWXMethods(Class c)
1579 #if OBJC_API_VERSION < 2
1580 static objc_method wxmethods[] =
1584 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1585 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1586 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1588 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1589 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1590 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1592 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1594 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1595 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1596 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1598 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
1600 wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1601 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1602 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1604 wxOSX_CLASS_ADD_METHOD(c, @selector(cursorUpdate:), (IMP) wxOSX_cursorUpdate, "v@:@" )
1606 wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1607 wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1608 wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1610 wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1612 wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
1614 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1615 wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1616 wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1618 #if !wxOSX_USE_NATIVE_FLIPPED
1619 wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1621 wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1623 wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1624 wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1626 #if wxUSE_DRAG_AND_DROP
1627 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1628 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1629 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1630 wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1633 #if OBJC_API_VERSION < 2
1635 static int method_count = WXSIZEOF( wxmethods );
1636 static objc_method_list *wxmethodlist = NULL;
1637 if ( wxmethodlist == NULL )
1639 wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1640 memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1641 wxmethodlist->method_count = method_count;
1642 wxmethodlist->obsolete = 0;
1644 class_addMethods( c, wxmethodlist );
1649 // C++ implementation class
1652 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1654 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl, bool isUserPane ) :
1655 wxWidgetImpl( peer, isRootControl, isUserPane )
1660 // check if the user wants to create the control initially hidden
1661 if ( !peer->IsShown() )
1662 SetVisibility(false);
1664 // gc aware handling
1666 CFRetain(m_osxView);
1667 [m_osxView release];
1670 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1675 void wxWidgetCocoaImpl::Init()
1678 #if !wxOSX_USE_NATIVE_FLIPPED
1681 m_lastKeyDownEvent = NULL;
1682 m_hasEditor = false;
1685 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1687 RemoveAssociations( this );
1689 if ( !IsRootControl() )
1691 NSView *sv = [m_osxView superview];
1693 [m_osxView removeFromSuperview];
1695 // gc aware handling
1697 CFRelease(m_osxView);
1700 bool wxWidgetCocoaImpl::IsVisible() const
1702 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1705 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1707 [m_osxView setHidden:(visible ? NO:YES)];
1710 // ----------------------------------------------------------------------------
1711 // window animation stuff
1712 // ----------------------------------------------------------------------------
1714 // define a delegate used to refresh the window during animation
1715 @interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
1721 - (id)init:(wxWindow *)win;
1725 // NSAnimationDelegate methods
1726 - (void)animationDidEnd:(NSAnimation*)animation;
1727 - (void)animation:(NSAnimation*)animation
1728 didReachProgressMark:(NSAnimationProgress)progress;
1731 @implementation wxNSAnimationDelegate
1733 - (id)init:(wxWindow *)win
1735 self = [super init];
1748 - (void)animation:(NSAnimation*)animation
1749 didReachProgressMark:(NSAnimationProgress)progress
1751 wxUnusedVar(animation);
1752 wxUnusedVar(progress);
1754 m_win->SendSizeEvent();
1757 - (void)animationDidEnd:(NSAnimation*)animation
1759 wxUnusedVar(animation);
1767 wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1769 wxShowEffect effect,
1772 // create the dictionary describing the animation to perform on this view
1774 viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1775 NSMutableDictionary * const
1776 dict = [NSMutableDictionary dictionaryWithCapacity:4];
1777 [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1779 // determine the start and end rectangles assuming we're hiding the window
1780 const wxRect rectOrig = win->GetRect();
1788 if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1789 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1790 effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1791 else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1792 effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1793 effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1794 else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1795 effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1796 effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1797 else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1798 effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1799 effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1804 case wxSHOW_EFFECT_ROLL_TO_LEFT:
1805 case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1809 case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1810 case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1811 rectEnd.x = rectStart.GetRight();
1815 case wxSHOW_EFFECT_ROLL_TO_TOP:
1816 case wxSHOW_EFFECT_SLIDE_TO_TOP:
1820 case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1821 case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1822 rectEnd.y = rectStart.GetBottom();
1826 case wxSHOW_EFFECT_EXPAND:
1827 rectEnd.x = rectStart.x + rectStart.width / 2;
1828 rectEnd.y = rectStart.y + rectStart.height / 2;
1833 case wxSHOW_EFFECT_BLEND:
1834 [dict setObject:(show ? NSViewAnimationFadeInEffect
1835 : NSViewAnimationFadeOutEffect)
1836 forKey:NSViewAnimationEffectKey];
1839 case wxSHOW_EFFECT_NONE:
1840 case wxSHOW_EFFECT_MAX:
1841 wxFAIL_MSG( "unexpected animation effect" );
1845 wxFAIL_MSG( "unknown animation effect" );
1851 // we need to restore it to the original rectangle instead of making it
1853 wxSwap(rectStart, rectEnd);
1855 // and as the window is currently hidden, we need to show it for the
1856 // animation to be visible at all (but don't restore it at its full
1857 // rectangle as it shouldn't appear immediately)
1858 win->SetSize(rectStart);
1862 NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1863 ? [(NSView *)viewOrWin superview]
1865 const NSRect rStart = wxToNSRect(parentView, rectStart);
1866 const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1868 [dict setObject:[NSValue valueWithRect:rStart]
1869 forKey:NSViewAnimationStartFrameKey];
1870 [dict setObject:[NSValue valueWithRect:rEnd]
1871 forKey:NSViewAnimationEndFrameKey];
1873 // create an animation using the values in the above dictionary
1874 NSViewAnimation * const
1875 anim = [[NSViewAnimation alloc]
1876 initWithViewAnimations:[NSArray arrayWithObject:dict]];
1880 // what is a good default duration? Windows uses 200ms, Web frameworks
1881 // use anything from 250ms to 1s... choose something in the middle
1885 [anim setDuration:timeout/1000.]; // duration is in seconds here
1887 // if the window being animated changes its layout depending on its size
1888 // (which is almost always the case) we need to redo it during animation
1890 // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1891 // controls in wxInfoBar visibly jump around)
1892 const int NUM_LAYOUTS = 20;
1893 for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1894 [anim addProgressMark:f];
1896 wxNSAnimationDelegate * const
1897 animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1898 [anim setDelegate:animDelegate];
1899 [anim startAnimation];
1901 // Cocoa is capable of doing animation asynchronously or even from separate
1902 // thread but wx API doesn't provide any way to be notified about the
1903 // animation end and without this we really must ensure that the window has
1904 // the expected (i.e. the same as if a simple Show() had been used) size
1905 // when we return, so block here until the animation finishes
1907 // notice that because the default animation mode is NSAnimationBlocking,
1908 // no user input events ought to be processed from here
1910 wxEventLoopGuarantor ensureEventLoopExistence;
1911 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1912 while ( ![animDelegate isDone] )
1918 // NSViewAnimation is smart enough to hide the NSView being animated at
1919 // the end but we also must ensure that it's hidden for wx too
1922 // and we must also restore its size because it isn't expected to
1923 // change just because the window was hidden
1924 win->SetSize(rectOrig);
1928 // refresh it once again after the end to ensure that everything is in
1930 win->SendSizeEvent();
1933 [anim setDelegate:nil];
1934 [animDelegate release];
1940 bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
1941 wxShowEffect effect,
1944 return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
1947 /* note that the drawing order between siblings is not defined under 10.4 */
1948 /* only starting from 10.5 the subview order is respected */
1950 /* NSComparisonResult is typedef'd as an enum pre-Leopard but typedef'd as
1951 * NSInteger post-Leopard. Pre-Leopard the Cocoa toolkit expects a function
1952 * returning int and not NSComparisonResult. Post-Leopard the Cocoa toolkit
1953 * expects a function returning the new non-enum NSComparsionResult.
1954 * Hence we create a typedef named CocoaWindowCompareFunctionResult.
1956 #if defined(NSINTEGER_DEFINED)
1957 typedef NSComparisonResult CocoaWindowCompareFunctionResult;
1959 typedef int CocoaWindowCompareFunctionResult;
1962 class CocoaWindowCompareContext
1964 wxDECLARE_NO_COPY_CLASS(CocoaWindowCompareContext);
1966 CocoaWindowCompareContext(); // Not implemented
1967 CocoaWindowCompareContext(NSView *target, NSArray *subviews)
1970 // Cocoa sorts subviews in-place.. make a copy
1971 m_subviews = [subviews copy];
1974 ~CocoaWindowCompareContext()
1975 { // release the copy
1976 [m_subviews release];
1979 { return m_target; }
1982 { return m_subviews; }
1984 /* Helper function that returns the comparison based off of the original ordering */
1985 CocoaWindowCompareFunctionResult CompareUsingOriginalOrdering(id first, id second)
1987 NSUInteger firstI = [m_subviews indexOfObjectIdenticalTo:first];
1988 NSUInteger secondI = [m_subviews indexOfObjectIdenticalTo:second];
1989 // NOTE: If either firstI or secondI is NSNotFound then it will be NSIntegerMax and thus will
1990 // likely compare higher than the other view which is reasonable considering the only way that
1991 // can happen is if the subview was added after our call to subviews but before the call to
1992 // sortSubviewsUsingFunction:context:. Thus we don't bother checking. Particularly because
1993 // that case should never occur anyway because that would imply a multi-threaded GUI call
1994 // which is a big no-no with Cocoa.
1996 // Subviews are ordered from back to front meaning one that is already lower will have an lower index.
1997 NSComparisonResult result = (firstI < secondI)
1998 ? NSOrderedAscending /* -1 */
1999 : (firstI > secondI)
2000 ? NSOrderedDescending /* 1 */
2001 : NSOrderedSame /* 0 */;
2006 /* The subview we are trying to Raise or Lower */
2008 /* A copy of the original array of subviews */
2009 NSArray *m_subviews;
2012 /* Causes Cocoa to raise the target view to the top of the Z-Order by telling the sort function that
2013 * the target view is always higher than every other view. When comparing two views neither of
2014 * which is the target, it returns the correct response based on the original ordering
2016 static CocoaWindowCompareFunctionResult CocoaRaiseWindowCompareFunction(id first, id second, void *ctx)
2018 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
2019 // first should be ordered higher
2020 if(first==compareContext->target())
2021 return NSOrderedDescending;
2022 // second should be ordered higher
2023 if(second==compareContext->target())
2024 return NSOrderedAscending;
2025 return compareContext->CompareUsingOriginalOrdering(first,second);
2028 void wxWidgetCocoaImpl::Raise()
2030 NSView* nsview = m_osxView;
2032 NSView *superview = [nsview superview];
2033 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
2035 [superview sortSubviewsUsingFunction:
2036 CocoaRaiseWindowCompareFunction
2037 context: &compareContext];
2041 /* Causes Cocoa to lower the target view to the bottom of the Z-Order by telling the sort function that
2042 * the target view is always lower than every other view. When comparing two views neither of
2043 * which is the target, it returns the correct response based on the original ordering
2045 static CocoaWindowCompareFunctionResult CocoaLowerWindowCompareFunction(id first, id second, void *ctx)
2047 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
2048 // first should be ordered lower
2049 if(first==compareContext->target())
2050 return NSOrderedAscending;
2051 // second should be ordered lower
2052 if(second==compareContext->target())
2053 return NSOrderedDescending;
2054 return compareContext->CompareUsingOriginalOrdering(first,second);
2057 void wxWidgetCocoaImpl::Lower()
2059 NSView* nsview = m_osxView;
2061 NSView *superview = [nsview superview];
2062 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
2064 [superview sortSubviewsUsingFunction:
2065 CocoaLowerWindowCompareFunction
2066 context: &compareContext];
2069 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
2074 // We should do something like this, but it wasn't working in 10.4.
2075 if (GetNeedsDisplay() )
2079 NSRect r = wxToNSRect( [m_osxView superview], *rect );
2080 NSSize offset = NSMakeSize((float)dx, (float)dy);
2081 [m_osxView scrollRect:r by:offset];
2085 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
2087 wxWindowMac* parent = GetWXPeer()->GetParent();
2088 // under Cocoa we might have a contentView in the wxParent to which we have to
2089 // adjust the coordinates
2090 if (parent && [m_osxView superview] != parent->GetHandle() )
2092 int cx = 0,cy = 0,cw = 0,ch = 0;
2093 if ( parent->GetPeer() )
2095 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2100 [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
2101 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
2102 [m_osxView setFrame:r];
2103 [[m_osxView superview] setNeedsDisplayInRect:r];
2106 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
2108 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
2112 // under Cocoa we might have a contentView in the wxParent to which we have to
2113 // adjust the coordinates
2114 wxWindowMac* parent = GetWXPeer()->GetParent();
2115 if (parent && [m_osxView superview] != parent->GetHandle() )
2117 int cx = 0,cy = 0,cw = 0,ch = 0;
2118 if ( parent->GetPeer() )
2120 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2127 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
2129 NSRect rect = [m_osxView frame];
2130 width = (int)rect.size.width;
2131 height = (int)rect.size.height;
2134 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
2136 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
2138 NSView* cv = [m_osxView contentView];
2140 NSRect bounds = [m_osxView bounds];
2141 NSRect rect = [cv frame];
2143 int y = (int)rect.origin.y;
2144 int x = (int)rect.origin.x;
2145 if ( ![ m_osxView isFlipped ] )
2146 y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
2149 width = (int)rect.size.width;
2150 height = (int)rect.size.height;
2155 GetSize( width, height );
2159 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
2162 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
2164 [m_osxView setNeedsDisplay:YES];
2167 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
2169 return [m_osxView needsDisplay];
2172 bool wxWidgetCocoaImpl::CanFocus() const
2174 return [m_osxView canBecomeKeyView] == YES;
2177 bool wxWidgetCocoaImpl::HasFocus() const
2179 return ( FindFocus() == m_osxView );
2182 bool wxWidgetCocoaImpl::SetFocus()
2187 // TODO remove if no issues arise: should not raise the window, only assign focus
2188 //[[m_osxView window] makeKeyAndOrderFront:nil] ;
2189 [[m_osxView window] makeFirstResponder: m_osxView] ;
2193 void wxWidgetCocoaImpl::SetDropTarget(wxDropTarget* target)
2195 [m_osxView unregisterDraggedTypes];
2197 if ( target == NULL )
2200 wxDataObject* dobj = target->GetDataObject();
2204 CFMutableArrayRef typesarray = CFArrayCreateMutable(kCFAllocatorDefault,0,&kCFTypeArrayCallBacks);
2205 dobj->AddSupportedTypes(typesarray);
2206 NSView* targetView = m_osxView;
2207 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2208 targetView = [(NSScrollView*) m_osxView documentView];
2210 [targetView registerForDraggedTypes:(NSArray*)typesarray];
2211 CFRelease(typesarray);
2215 void wxWidgetCocoaImpl::RemoveFromParent()
2217 [m_osxView removeFromSuperview];
2220 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
2222 NSView* container = parent->GetWXWidget() ;
2223 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
2224 [container addSubview:m_osxView];
2226 if( m_wxPeer->IsFrozen() )
2227 [[m_osxView window] disableFlushWindow];
2230 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
2232 NSView* targetView = m_osxView;
2233 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2234 targetView = [(NSScrollView*) m_osxView documentView];
2236 if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
2238 [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2239 green:(CGFloat) (col.Green() / 255.0)
2240 blue:(CGFloat) (col.Blue() / 255.0)
2241 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2245 bool wxWidgetCocoaImpl::SetBackgroundStyle( wxBackgroundStyle style )
2247 BOOL opaque = ( style == wxBG_STYLE_PAINT );
2249 if ( [m_osxView respondsToSelector:@selector(setOpaque:) ] )
2251 [m_osxView setOpaque: opaque];
2257 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
2259 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
2261 wxCFStringRef cf( title , encoding );
2262 [m_osxView setTitle:cf.AsNSString()];
2264 else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
2266 wxCFStringRef cf( title , encoding );
2267 [m_osxView setStringValue:cf.AsNSString()];
2272 void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
2274 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
2275 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
2276 *pt = wxFromNSPoint( to->GetWXWidget(), p );
2279 wxInt32 wxWidgetCocoaImpl::GetValue() const
2281 return [(NSControl*)m_osxView intValue];
2284 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
2286 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
2288 [m_osxView setIntValue:v];
2290 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
2292 [m_osxView setFloatValue:(double)v];
2294 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
2296 [m_osxView setDoubleValue:(double)v];
2300 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
2302 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
2304 [m_osxView setMinValue:(double)v];
2308 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
2310 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
2312 [m_osxView setMaxValue:(double)v];
2316 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
2318 if ( [m_osxView respondsToSelector:@selector(minValue)] )
2320 return (int)[m_osxView minValue];
2325 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
2327 if ( [m_osxView respondsToSelector:@selector(maxValue)] )
2329 return (int)[m_osxView maxValue];
2334 wxBitmap wxWidgetCocoaImpl::GetBitmap() const
2338 // TODO: how to create a wxBitmap from NSImage?
2340 if ( [m_osxView respondsToSelector:@selector(image:)] )
2341 bmp = [m_osxView image];
2347 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
2349 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
2352 [m_osxView setImage:bitmap.GetNSImage()];
2354 [m_osxView setImage:nil];
2356 [m_osxView setNeedsDisplay:YES];
2360 void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
2362 if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
2364 NSCellImagePosition pos;
2384 wxFAIL_MSG( "invalid image position" );
2388 [m_osxView setImagePosition:pos];
2392 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
2394 // implementation in subclass
2397 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
2399 r->x = r->y = r->width = r->height = 0;
2401 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
2403 NSRect former = [m_osxView frame];
2404 [m_osxView sizeToFit];
2405 NSRect best = [m_osxView frame];
2406 [m_osxView setFrame:former];
2407 r->width = (int)best.size.width;
2408 r->height = (int)best.size.height;
2412 bool wxWidgetCocoaImpl::IsEnabled() const
2414 NSView* targetView = m_osxView;
2415 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2416 targetView = [(NSScrollView*) m_osxView documentView];
2418 if ( [targetView respondsToSelector:@selector(isEnabled) ] )
2419 return [targetView isEnabled];
2423 void wxWidgetCocoaImpl::Enable( bool enable )
2425 NSView* targetView = m_osxView;
2426 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2427 targetView = [(NSScrollView*) m_osxView documentView];
2429 if ( [targetView respondsToSelector:@selector(setEnabled:) ] )
2430 [targetView setEnabled:enable];
2433 void wxWidgetCocoaImpl::PulseGauge()
2437 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
2441 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
2443 NSControlSize size = NSRegularControlSize;
2447 case wxWINDOW_VARIANT_NORMAL :
2448 size = NSRegularControlSize;
2451 case wxWINDOW_VARIANT_SMALL :
2452 size = NSSmallControlSize;
2455 case wxWINDOW_VARIANT_MINI :
2456 size = NSMiniControlSize;
2459 case wxWINDOW_VARIANT_LARGE :
2460 size = NSRegularControlSize;
2464 wxFAIL_MSG(wxT("unexpected window variant"));
2467 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
2468 [m_osxView setControlSize:size];
2469 else if ([m_osxView respondsToSelector:@selector(cell)])
2471 id cell = [(id)m_osxView cell];
2472 if ([cell respondsToSelector:@selector(setControlSize:)])
2473 [cell setControlSize:size];
2476 // we need to propagate this to inner views as well
2477 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2479 NSView* targetView = [(NSScrollView*) m_osxView documentView];
2481 if ( [targetView respondsToSelector:@selector(setControlSize:)] )
2482 [targetView setControlSize:size];
2483 else if ([targetView respondsToSelector:@selector(cell)])
2485 id cell = [(id)targetView cell];
2486 if ([cell respondsToSelector:@selector(setControlSize:)])
2487 [cell setControlSize:size];
2492 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&col, long, bool)
2494 NSView* targetView = m_osxView;
2495 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2496 targetView = [(NSScrollView*) m_osxView documentView];
2498 if ([targetView respondsToSelector:@selector(setFont:)])
2499 [targetView setFont: font.OSXGetNSFont()];
2500 if ([targetView respondsToSelector:@selector(setTextColor:)])
2501 [targetView setTextColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2502 green:(CGFloat) (col.Green() / 255.0)
2503 blue:(CGFloat) (col.Blue() / 255.0)
2504 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2507 void wxWidgetCocoaImpl::SetToolTip(wxToolTip* tooltip)
2511 wxCFStringRef cf( tooltip->GetTip() , m_wxPeer->GetFont().GetEncoding() );
2512 [m_osxView setToolTip: cf.AsNSString()];
2516 [m_osxView setToolTip:nil];
2520 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
2522 WXWidget c = control ? control : (WXWidget) m_osxView;
2523 wxWidgetImpl::Associate( c, this ) ;
2524 if ([c respondsToSelector:@selector(setAction:)])
2527 [c setAction: @selector(controlAction:)];
2528 if ([c respondsToSelector:@selector(setDoubleAction:)])
2530 [c setDoubleAction: @selector(controlDoubleAction:)];
2534 NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingCursorUpdate|NSTrackingMouseMoved|NSTrackingActiveAlways|NSTrackingInVisibleRect;
2535 NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: NSZeroRect options: options owner: m_osxView userInfo: nil];
2536 [m_osxView addTrackingArea: area];
2540 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
2542 wxKeyEvent wxevent(wxEVT_CHAR);
2543 SetupKeyEvent( wxevent, event, text );
2545 return GetWXPeer()->OSXHandleKeyEvent(wxevent);
2548 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
2550 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
2551 SetupKeyEvent( wxevent, event );
2553 // Generate wxEVT_CHAR_HOOK before sending any other events but only when
2554 // the key is pressed, not when it's released (the type of wxevent is
2555 // changed by SetupKeyEvent() so it can be wxEVT_KEY_UP too by now).
2556 if ( wxevent.GetEventType() == wxEVT_KEY_DOWN )
2558 wxKeyEvent eventHook(wxEVT_CHAR_HOOK, wxevent);
2559 if ( GetWXPeer()->OSXHandleKeyEvent(eventHook)
2560 && !eventHook.IsNextEventAllowed() )
2564 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
2566 // this will fire higher level events, like insertText, to help
2567 // us handle EVT_CHAR, etc.
2571 if ( [event type] == NSKeyDown)
2573 long keycode = wxOSXTranslateCocoaKey( event, wxEVT_CHAR );
2575 if ( (keycode > 0 && keycode < WXK_SPACE) || keycode == WXK_DELETE || keycode >= WXK_START )
2577 // eventually we could setup a doCommandBySelector catcher and retransform this into the wx key chars
2578 wxKeyEvent wxevent2(wxevent) ;
2579 wxevent2.SetEventType(wxEVT_CHAR);
2580 SetupKeyEvent( wxevent2, event );
2581 wxevent2.m_keyCode = keycode;
2582 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2584 else if (wxevent.CmdDown())
2586 wxKeyEvent wxevent2(wxevent) ;
2587 wxevent2.SetEventType(wxEVT_CHAR);
2588 SetupKeyEvent( wxevent2, event );
2589 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2593 if ( IsUserPane() && !wxevent.CmdDown() )
2595 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2596 [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
2598 [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
2608 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
2610 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
2611 SetupMouseEvent(wxevent , event) ;
2612 bool result = GetWXPeer()->HandleWindowEvent(wxevent);
2614 (void)SetupCursor(event);
2619 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
2621 wxWindow* thisWindow = GetWXPeer();
2622 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
2624 thisWindow->MacInvalidateBorders();
2627 if ( receivedFocus )
2629 wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
2630 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
2631 thisWindow->HandleWindowEvent(eventFocus);
2634 if ( thisWindow->GetCaret() )
2635 thisWindow->GetCaret()->OnSetFocus();
2638 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
2639 event.SetEventObject(thisWindow);
2641 event.SetWindow(otherWindow->GetWXPeer());
2642 thisWindow->HandleWindowEvent(event) ;
2644 else // !receivedFocus
2647 if ( thisWindow->GetCaret() )
2648 thisWindow->GetCaret()->OnKillFocus();
2651 wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
2653 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
2654 event.SetEventObject(thisWindow);
2656 event.SetWindow(otherWindow->GetWXPeer());
2657 thisWindow->HandleWindowEvent(event) ;
2661 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
2665 NSPoint location = [NSEvent mouseLocation];
2666 location = [[m_osxView window] convertScreenToBase:location];
2667 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
2669 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
2671 [(NSCursor*)cursor.GetHCURSOR() set];
2676 void wxWidgetCocoaImpl::CaptureMouse()
2678 // TODO remove if we don't get into problems with cursor settings
2679 // [[m_osxView window] disableCursorRects];
2682 void wxWidgetCocoaImpl::ReleaseMouse()
2684 // TODO remove if we don't get into problems with cursor settings
2685 // [[m_osxView window] enableCursorRects];
2688 #if !wxOSX_USE_NATIVE_FLIPPED
2690 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
2692 m_isFlipped = flipped;
2697 void wxWidgetCocoaImpl::SetDrawingEnabled(bool enabled)
2701 [[m_osxView window] enableFlushWindow];
2702 [m_osxView setNeedsDisplay:YES];
2706 [[m_osxView window] disableFlushWindow];
2713 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
2714 wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
2715 long WXUNUSED(style), long WXUNUSED(extraStyle))
2717 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
2718 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
2720 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v, false, true );
2724 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
2726 NSWindow* tlw = now->GetWXWindow();
2728 wxWidgetCocoaImpl* c = NULL;
2729 if ( now->IsNativeWindowWrapper() )
2731 NSView* cv = [tlw contentView];
2732 c = new wxWidgetCocoaImpl( now, cv, true );
2735 // increase ref count, because the impl destructor will decrement it again
2737 if ( !now->IsShown() )
2743 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2744 c = new wxWidgetCocoaImpl( now, v, true );
2745 c->InstallEventHandler();
2746 [tlw setContentView:v];