1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/cocoa/window.mm
3 // Purpose: widgets (non tlw) for cocoa
4 // Author: Stefan Csomor
8 // Copyright: (c) Stefan Csomor
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 #include "wx/wxprec.h"
15 #include "wx/dcclient.h"
18 #include "wx/textctrl.h"
19 #include "wx/combobox.h"
23 #include "wx/osx/private.h"
26 #include "wx/evtloop.h"
32 #if wxUSE_DRAG_AND_DROP
37 #include "wx/tooltip.h"
40 #include <objc/objc-runtime.h>
42 // Get the window with the focus
44 NSView* GetViewFromResponder( NSResponder* responder )
47 if ( [responder isKindOfClass:[NSTextView class]] )
49 NSView* delegate = (NSView*) [(NSTextView*)responder delegate];
50 if ( [delegate isKindOfClass:[NSTextField class] ] )
53 view = (NSView*) responder;
57 if ( [responder isKindOfClass:[NSView class]] )
58 view = (NSView*) responder;
63 NSView* GetFocusedViewInWindow( NSWindow* keyWindow )
65 NSView* focusedView = nil;
66 if ( keyWindow != nil )
67 focusedView = GetViewFromResponder([keyWindow firstResponder]);
72 WXWidget wxWidgetImpl::FindFocus()
74 return GetFocusedViewInWindow( [NSApp keyWindow] );
77 NSRect wxOSXGetFrameForControl( wxWindowMac* window , const wxPoint& pos , const wxSize &size , bool adjustForOrigin )
81 window->MacGetBoundsForControl( pos , size , x , y, w, h , adjustForOrigin ) ;
82 wxRect bounds(x,y,w,h);
83 NSView* sv = (window->GetParent()->GetHandle() );
85 return wxToNSRect( sv, bounds );
88 @interface wxNSView : NSView
90 NSTrackingRectTag rectTag;
91 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
92 NSTrackingArea* _trackingArea;
96 // the tracking tag is needed to track mouse enter / exit events
97 - (void) setTrackingTag: (NSTrackingRectTag)tag;
98 - (NSTrackingRectTag) trackingTag;
99 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
100 // under 10.5 we can also track mouse moved events on non-focused windows if
101 // we use the new NSTrackingArea APIs.
102 - (void) updateTrackingArea;
103 - (NSTrackingArea*) trackingArea;
107 @interface NSView(PossibleMethods)
108 - (void)setTitle:(NSString *)aString;
109 - (void)setStringValue:(NSString *)aString;
110 - (void)setIntValue:(int)anInt;
111 - (void)setFloatValue:(float)aFloat;
112 - (void)setDoubleValue:(double)aDouble;
116 - (void)setMinValue:(double)aDouble;
117 - (void)setMaxValue:(double)aDouble;
122 - (void)setEnabled:(BOOL)flag;
124 - (void)setImage:(NSImage *)image;
125 - (void)setControlSize:(NSControlSize)size;
127 - (void)setFont:(NSFont *)fontObject;
131 - (void)setTarget:(id)anObject;
132 - (void)setAction:(SEL)aSelector;
133 - (void)setDoubleAction:(SEL)aSelector;
134 - (void)setBackgroundColor:(NSColor*)aColor;
135 - (void)setOpaque:(BOOL)opaque;
136 - (void)setTextColor:(NSColor *)color;
137 - (void)setImagePosition:(NSCellImagePosition)aPosition;
140 long wxOSXTranslateCocoaKey( NSEvent* event )
144 if ([event type] != NSFlagsChanged)
146 NSString* s = [event charactersIgnoringModifiers];
147 // backspace char reports as delete w/modifiers for some reason
150 switch ( [s characterAtIndex:0] )
157 case NSUpArrowFunctionKey :
160 case NSDownArrowFunctionKey :
163 case NSLeftArrowFunctionKey :
166 case NSRightArrowFunctionKey :
169 case NSInsertFunctionKey :
172 case NSDeleteFunctionKey :
175 case NSHomeFunctionKey :
178 // case NSBeginFunctionKey :
179 // retval = WXK_BEGIN;
181 case NSEndFunctionKey :
184 case NSPageUpFunctionKey :
187 case NSPageDownFunctionKey :
188 retval = WXK_PAGEDOWN;
190 case NSHelpFunctionKey :
194 int intchar = [s characterAtIndex: 0];
195 if ( intchar >= NSF1FunctionKey && intchar <= NSF24FunctionKey )
196 retval = WXK_F1 + (intchar - NSF1FunctionKey );
202 // Some keys don't seem to have constants. The code mimics the approach
203 // taken by WebKit. See:
204 // http://trac.webkit.org/browser/trunk/WebCore/platform/mac/KeyEventMac.mm
205 switch( [event keyCode] )
210 retval = WXK_COMMAND;
214 retval = WXK_CAPITAL;
217 case 56: // Left Shift
218 case 60: // Right Shift
223 case 61: // Right Alt
227 case 59: // Left Ctrl
228 case 62: // Right Ctrl
229 retval = WXK_CONTROL;
241 retval = WXK_NUMPAD_DIVIDE;
244 retval = WXK_NUMPAD_MULTIPLY;
247 retval = WXK_NUMPAD_SUBTRACT;
250 retval = WXK_NUMPAD_ADD;
253 retval = WXK_NUMPAD_ENTER;
256 retval = WXK_NUMPAD_DECIMAL;
259 retval = WXK_NUMPAD0;
262 retval = WXK_NUMPAD1;
265 retval = WXK_NUMPAD2;
268 retval = WXK_NUMPAD3;
271 retval = WXK_NUMPAD4;
274 retval = WXK_NUMPAD5;
277 retval = WXK_NUMPAD6;
280 retval = WXK_NUMPAD7;
283 retval = WXK_NUMPAD8;
286 retval = WXK_NUMPAD9;
289 //retval = [event keyCode];
295 void wxWidgetCocoaImpl::SetupKeyEvent(wxKeyEvent &wxevent , NSEvent * nsEvent, NSString* charString)
297 UInt32 modifiers = [nsEvent modifierFlags] ;
298 int eventType = [nsEvent type];
300 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
301 wxevent.m_controlDown = modifiers & NSControlKeyMask;
302 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
303 wxevent.m_metaDown = modifiers & NSCommandKeyMask;
305 wxevent.m_rawCode = [nsEvent keyCode];
306 wxevent.m_rawFlags = modifiers;
308 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
311 if ( eventType != NSFlagsChanged )
313 NSString* nschars = [nsEvent charactersIgnoringModifiers];
316 // if charString is set, it did not come from key up / key down
317 wxevent.SetEventType( wxEVT_CHAR );
318 chars = wxCFStringRef::AsString(charString);
322 chars = wxCFStringRef::AsString(nschars);
326 int aunichar = chars.Length() > 0 ? chars[0] : 0;
329 if (wxevent.GetEventType() != wxEVT_CHAR)
331 keyval = wxOSXTranslateCocoaKey(nsEvent) ;
335 wxevent.SetEventType( wxEVT_KEY_DOWN ) ;
338 wxevent.SetEventType( wxEVT_KEY_UP ) ;
340 case NSFlagsChanged :
344 wxevent.SetEventType( wxevent.m_controlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
347 wxevent.SetEventType( wxevent.m_shiftDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
350 wxevent.SetEventType( wxevent.m_altDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
353 wxevent.SetEventType( wxevent.m_metaDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
364 if ( wxevent.GetEventType() == wxEVT_KEY_UP || wxevent.GetEventType() == wxEVT_KEY_DOWN )
365 keyval = wxToupper( aunichar ) ;
371 wxevent.m_uniChar = aunichar;
373 wxevent.m_keyCode = keyval;
375 wxWindowMac* peer = GetWXPeer();
378 wxevent.SetEventObject(peer);
379 wxevent.SetId(peer->GetId()) ;
383 UInt32 g_lastButton = 0 ;
384 bool g_lastButtonWasFakeRight = false ;
386 // better scroll wheel support
387 // see http://lists.apple.com/archives/cocoa-dev/2007/Feb/msg00050.html
389 @interface NSEvent (DeviceDelta)
390 - (CGFloat)deviceDeltaX;
391 - (CGFloat)deviceDeltaY;
394 void wxWidgetCocoaImpl::SetupMouseEvent( wxMouseEvent &wxevent , NSEvent * nsEvent )
396 int eventType = [nsEvent type];
397 UInt32 modifiers = [nsEvent modifierFlags] ;
399 NSPoint locationInWindow = [nsEvent locationInWindow];
401 // adjust coordinates for the window of the target view
402 if ( [nsEvent window] != [m_osxView window] )
404 if ( [nsEvent window] != nil )
405 locationInWindow = [[nsEvent window] convertBaseToScreen:locationInWindow];
407 if ( [m_osxView window] != nil )
408 locationInWindow = [[m_osxView window] convertScreenToBase:locationInWindow];
411 NSPoint locationInView = [m_osxView convertPoint:locationInWindow fromView:nil];
412 wxPoint locationInViewWX = wxFromNSPoint( m_osxView, locationInView );
414 // these parameters are not given for all events
415 UInt32 button = [nsEvent buttonNumber];
416 UInt32 clickCount = 0;
418 wxevent.m_x = locationInViewWX.x;
419 wxevent.m_y = locationInViewWX.y;
420 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
421 wxevent.m_controlDown = modifiers & NSControlKeyMask;
422 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
423 wxevent.m_metaDown = modifiers & NSCommandKeyMask;
424 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
426 UInt32 mouseChord = 0;
430 case NSLeftMouseDown :
431 case NSLeftMouseDragged :
434 case NSRightMouseDown :
435 case NSRightMouseDragged :
438 case NSOtherMouseDown :
439 case NSOtherMouseDragged :
444 // a control click is interpreted as a right click
445 bool thisButtonIsFakeRight = false ;
446 if ( button == 0 && (modifiers & NSControlKeyMask) )
449 thisButtonIsFakeRight = true ;
452 // otherwise we report double clicks by connecting a left click with a ctrl-left click
453 if ( clickCount > 1 && button != g_lastButton )
456 // we must make sure that our synthetic 'right' button corresponds in
457 // mouse down, moved and mouse up, and does not deliver a right down and left up
460 case NSLeftMouseDown :
461 case NSRightMouseDown :
462 case NSOtherMouseDown :
463 g_lastButton = button ;
464 g_lastButtonWasFakeRight = thisButtonIsFakeRight ;
471 g_lastButtonWasFakeRight = false ;
473 else if ( g_lastButton == 1 && g_lastButtonWasFakeRight )
474 button = g_lastButton ;
476 // Adjust the chord mask to remove the primary button and add the
477 // secondary button. It is possible that the secondary button is
478 // already pressed, e.g. on a mouse connected to a laptop, but this
479 // possibility is ignored here:
480 if( thisButtonIsFakeRight && ( mouseChord & 1U ) )
481 mouseChord = ((mouseChord & ~1U) | 2U);
484 wxevent.m_leftDown = true ;
486 wxevent.m_rightDown = true ;
488 wxevent.m_middleDown = true ;
490 // translate into wx types
493 case NSLeftMouseDown :
494 case NSRightMouseDown :
495 case NSOtherMouseDown :
496 clickCount = [nsEvent clickCount];
500 wxevent.SetEventType( clickCount > 1 ? wxEVT_LEFT_DCLICK : wxEVT_LEFT_DOWN ) ;
504 wxevent.SetEventType( clickCount > 1 ? wxEVT_RIGHT_DCLICK : wxEVT_RIGHT_DOWN ) ;
508 wxevent.SetEventType( clickCount > 1 ? wxEVT_MIDDLE_DCLICK : wxEVT_MIDDLE_DOWN ) ;
517 case NSRightMouseUp :
518 case NSOtherMouseUp :
519 clickCount = [nsEvent clickCount];
523 wxevent.SetEventType( wxEVT_LEFT_UP ) ;
527 wxevent.SetEventType( wxEVT_RIGHT_UP ) ;
531 wxevent.SetEventType( wxEVT_MIDDLE_UP ) ;
544 wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ;
546 // see http://developer.apple.com/qa/qa2005/qa1453.html
547 // for more details on why we have to look for the exact type
549 const EventRef cEvent = (EventRef) [nsEvent eventRef];
550 bool isMouseScrollEvent = false;
552 isMouseScrollEvent = ::GetEventKind(cEvent) == kEventMouseScroll;
554 if ( isMouseScrollEvent )
556 deltaX = [nsEvent deviceDeltaX];
557 deltaY = [nsEvent deviceDeltaY];
561 deltaX = ([nsEvent deltaX] * 10);
562 deltaY = ([nsEvent deltaY] * 10);
565 wxevent.m_wheelDelta = 10;
566 wxevent.m_linesPerAction = 1;
568 if ( fabs(deltaX) > fabs(deltaY) )
570 wxevent.m_wheelAxis = 1;
571 wxevent.m_wheelRotation = (int)deltaX;
575 wxevent.m_wheelRotation = (int)deltaY;
581 case NSMouseEntered :
582 wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
585 wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
587 case NSLeftMouseDragged :
588 case NSRightMouseDragged :
589 case NSOtherMouseDragged :
591 wxevent.SetEventType( wxEVT_MOTION ) ;
597 wxevent.m_clickCount = clickCount;
598 wxWindowMac* peer = GetWXPeer();
601 wxevent.SetEventObject(peer);
602 wxevent.SetId(peer->GetId()) ;
606 @implementation wxNSView
610 static BOOL initialized = NO;
614 wxOSXCocoaClassAddWXMethods( self );
618 - (void) setTrackingTag: (NSTrackingRectTag)tag
623 - (NSTrackingRectTag) trackingTag
628 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
629 - (void) updateTrackingArea
633 [self removeTrackingArea: _trackingArea];
634 [_trackingArea release];
637 NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingMouseMoved|NSTrackingActiveAlways;
639 NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: [self bounds] options: options owner: self userInfo: nil];
640 [self addTrackingArea: area];
642 _trackingArea = area;
645 - (NSTrackingArea*) trackingArea
647 return _trackingArea;
656 #if wxUSE_DRAG_AND_DROP
658 // see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
659 // for details on the NSPasteboard -> PasteboardRef conversion
661 NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
663 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
665 return NSDragOperationNone;
667 return impl->draggingEntered(sender, self, _cmd);
670 void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
672 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
676 return impl->draggingExited(sender, self, _cmd);
679 NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
681 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
683 return NSDragOperationNone;
685 return impl->draggingUpdated(sender, self, _cmd);
688 BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
690 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
692 return NSDragOperationNone;
694 return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
699 void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
701 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
705 impl->mouseEvent(event, self, _cmd);
708 BOOL wxOSX_acceptsFirstMouse(NSView* WXUNUSED(self), SEL WXUNUSED(_cmd), NSEvent *WXUNUSED(event))
710 // This is needed to support click through, otherwise the first click on a window
711 // will not do anything unless it is the active window already.
715 void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
717 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
721 impl->keyEvent(event, self, _cmd);
724 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
726 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
730 impl->insertText(text, self, _cmd);
733 BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
735 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
739 return impl->performKeyEquivalent(event, self, _cmd);
742 BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
744 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
748 return impl->acceptsFirstResponder(self, _cmd);
751 BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
753 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
757 return impl->becomeFirstResponder(self, _cmd);
760 BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
762 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
766 return impl->resignFirstResponder(self, _cmd);
769 void wxOSX_resetCursorRects(NSView* self, SEL _cmd)
771 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
775 impl->resetCursorRects(self, _cmd);
778 BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
780 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
784 return impl->isFlipped(self, _cmd) ? YES:NO;
787 typedef void (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
789 void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
791 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
796 // OS X starts a NSUIHeartBeatThread for animating the default button in a
797 // dialog. This causes a drawRect of the active dialog from outside the
798 // main UI thread. This causes an occasional crash since the wx drawing
799 // objects (like wxPen) are not thread safe.
801 // Notice that NSUIHeartBeatThread seems to be undocumented and doing
802 // [NSWindow setAllowsConcurrentViewDrawing:NO] does not affect it.
803 if ( !wxThread::IsMain() )
805 // just call the superclass handler, we don't need any custom wx drawing
806 // here and it seems to work fine:
807 wxOSX_DrawRectHandlerPtr
808 superimpl = (wxOSX_DrawRectHandlerPtr)
809 [[self superclass] instanceMethodForSelector:_cmd];
810 superimpl(self, _cmd, rect);
813 #endif // wxUSE_THREADS
815 return impl->drawRect(&rect, self, _cmd);
818 void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
820 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
824 impl->controlAction(self, _cmd, sender);
827 void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
829 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
833 impl->controlDoubleAction(self, _cmd, sender);
836 unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
838 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
839 NSPasteboard *pboard = [sender draggingPasteboard];
840 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
842 wxWindow* wxpeer = GetWXPeer();
843 if ( wxpeer == NULL )
844 return NSDragOperationNone;
846 wxDropTarget* target = wxpeer->GetDropTarget();
847 if ( target == NULL )
848 return NSDragOperationNone;
850 wxDragResult result = wxDragNone;
851 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
852 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
854 if ( sourceDragMask & NSDragOperationLink )
856 else if ( sourceDragMask & NSDragOperationCopy )
858 else if ( sourceDragMask & NSDragOperationMove )
861 PasteboardRef pboardRef;
862 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
863 target->SetCurrentDragPasteboard(pboardRef);
864 result = target->OnEnter(pt.x, pt.y, result);
865 CFRelease(pboardRef);
867 NSDragOperation nsresult = NSDragOperationNone;
871 nsresult = NSDragOperationLink;
873 nsresult = NSDragOperationMove;
875 nsresult = NSDragOperationCopy;
882 void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
884 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
885 NSPasteboard *pboard = [sender draggingPasteboard];
887 wxWindow* wxpeer = GetWXPeer();
888 if ( wxpeer == NULL )
891 wxDropTarget* target = wxpeer->GetDropTarget();
892 if ( target == NULL )
895 PasteboardRef pboardRef;
896 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
897 target->SetCurrentDragPasteboard(pboardRef);
899 CFRelease(pboardRef);
902 unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
904 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
905 NSPasteboard *pboard = [sender draggingPasteboard];
906 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
908 wxWindow* wxpeer = GetWXPeer();
909 if ( wxpeer == NULL )
910 return NSDragOperationNone;
912 wxDropTarget* target = wxpeer->GetDropTarget();
913 if ( target == NULL )
914 return NSDragOperationNone;
916 wxDragResult result = wxDragNone;
917 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
918 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
920 if ( sourceDragMask & NSDragOperationLink )
922 else if ( sourceDragMask & NSDragOperationCopy )
924 else if ( sourceDragMask & NSDragOperationMove )
927 PasteboardRef pboardRef;
928 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
929 target->SetCurrentDragPasteboard(pboardRef);
930 result = target->OnDragOver(pt.x, pt.y, result);
931 CFRelease(pboardRef);
933 NSDragOperation nsresult = NSDragOperationNone;
937 nsresult = NSDragOperationLink;
939 nsresult = NSDragOperationMove;
941 nsresult = NSDragOperationCopy;
948 bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
950 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
952 NSPasteboard *pboard = [sender draggingPasteboard];
953 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
955 wxWindow* wxpeer = GetWXPeer();
956 wxDropTarget* target = wxpeer->GetDropTarget();
957 wxDragResult result = wxDragNone;
958 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
959 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
961 if ( sourceDragMask & NSDragOperationLink )
963 else if ( sourceDragMask & NSDragOperationCopy )
965 else if ( sourceDragMask & NSDragOperationMove )
968 PasteboardRef pboardRef;
969 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
970 target->SetCurrentDragPasteboard(pboardRef);
972 if (target->OnDrop(pt.x, pt.y))
973 result = target->OnData(pt.x, pt.y, result);
975 CFRelease(pboardRef);
977 return result != wxDragNone;
980 typedef void (*wxOSX_TextEventHandlerPtr)(NSView* self, SEL _cmd, NSString *event);
981 typedef void (*wxOSX_EventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
982 typedef BOOL (*wxOSX_PerformKeyEventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
983 typedef BOOL (*wxOSX_FocusHandlerPtr)(NSView* self, SEL _cmd);
984 typedef BOOL (*wxOSX_ResetCursorRectsHandlerPtr)(NSView* self, SEL _cmd);
986 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
988 if ( !DoHandleMouseEvent(event) )
990 // for plain NSView mouse events would propagate to parents otherwise
993 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
994 superimpl(slf, (SEL)_cmd, event);
999 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1001 if ( [event type] == NSKeyDown )
1003 // there are key equivalents that are not command-combos and therefore not handled by cocoa automatically,
1004 // therefore we call the menubar directly here, exit if the menu is handling the shortcut
1005 if ( [[[NSApplication sharedApplication] mainMenu] performKeyEquivalent:event] )
1008 m_lastKeyDownEvent = event;
1011 if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
1013 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1014 superimpl(slf, (SEL)_cmd, event);
1016 m_lastKeyDownEvent = NULL;
1019 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
1021 if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
1023 wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1024 superimpl(slf, (SEL)_cmd, text);
1029 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
1031 bool handled = false;
1033 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1034 SetupKeyEvent( wxevent, event );
1036 // because performKeyEquivalent is going up the entire view hierarchy, we don't have to
1037 // walk up the ancestors ourselves but let cocoa do it
1039 int command = m_wxPeer->GetAcceleratorTable()->GetCommand( wxevent );
1042 wxEvtHandler * const handler = m_wxPeer->GetEventHandler();
1044 wxCommandEvent command_event( wxEVT_COMMAND_MENU_SELECTED, command );
1045 handled = handler->ProcessEvent( command_event );
1049 // accelerators can also be used with buttons, try them too
1050 command_event.SetEventType(wxEVT_COMMAND_BUTTON_CLICKED);
1051 handled = handler->ProcessEvent( command_event );
1057 wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1058 return superimpl(slf, (SEL)_cmd, event);
1063 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
1066 return m_wxPeer->AcceptsFocus();
1069 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1070 return superimpl(slf, (SEL)_cmd);
1074 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
1076 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1077 // get the current focus before running becomeFirstResponder
1078 NSView* otherView = FindFocus();
1080 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1081 BOOL r = superimpl(slf, (SEL)_cmd);
1084 DoNotifyFocusEvent( true, otherWindow );
1090 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
1092 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1093 BOOL r = superimpl(slf, (SEL)_cmd);
1094 // get the current focus after running resignFirstResponder
1095 // note that this value isn't reliable, it might return the same view that
1097 NSView* otherView = FindFocus();
1098 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1100 // It doesn't make sense to notify about the loss of focus if we're not
1101 // really losing it and the window which has just gained focus is the same
1102 // one as this window itself. Of course, this should never happen in the
1103 // first place but somehow it does in wxGrid code and without this check we
1104 // enter into an infinite recursion, see #12267.
1105 if ( otherWindow == this )
1108 // NSTextViews have an editor as true responder, therefore the might get the
1109 // resign notification if their editor takes over, don't trigger any event then
1110 if ( r && !m_hasEditor)
1112 DoNotifyFocusEvent( false, otherWindow );
1117 void wxWidgetCocoaImpl::resetCursorRects(WXWidget slf, void *_cmd)
1119 wxWindow* wxpeer = GetWXPeer();
1122 NSCursor *cursor = (NSCursor*)wxpeer->GetCursor().GetHCURSOR();
1125 wxOSX_ResetCursorRectsHandlerPtr superimpl = (wxOSX_ResetCursorRectsHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1126 superimpl(slf, (SEL)_cmd);
1130 [slf addCursorRect: [slf bounds]
1136 bool wxWidgetCocoaImpl::isFlipped(WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1142 #define OSX_DEBUG_DRAWING 0
1144 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
1146 // preparing the update region
1149 const NSRect *rects;
1152 [slf getRectsBeingDrawn:&rects count:&count];
1153 for ( int i = 0 ; i < count ; ++i )
1155 updateRgn.Union(wxFromNSRect(slf, rects[i]));
1158 wxWindow* wxpeer = GetWXPeer();
1160 if ( wxpeer->MacGetLeftBorderSize() != 0 || wxpeer->MacGetTopBorderSize() != 0 )
1162 // as this update region is in native window locals we must adapt it to wx window local
1163 updateRgn.Offset( wxpeer->MacGetLeftBorderSize() , wxpeer->MacGetTopBorderSize() );
1166 if ( wxpeer->MacGetTopLevelWindow()->GetWindowStyle() & wxFRAME_SHAPED )
1168 int xoffset = 0, yoffset = 0;
1169 wxRegion rgn = wxpeer->MacGetTopLevelWindow()->GetShape();
1170 wxpeer->MacRootWindowToWindow( &xoffset, &yoffset );
1171 rgn.Offset( xoffset, yoffset );
1172 updateRgn.Intersect(rgn);
1175 wxpeer->GetUpdateRegion() = updateRgn;
1177 // setting up the drawing context
1179 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1180 CGContextSaveGState( context );
1182 #if OSX_DEBUG_DRAWING
1183 CGContextBeginPath( context );
1184 CGContextMoveToPoint(context, 0, 0);
1185 NSRect bounds = [slf bounds];
1186 CGContextAddLineToPoint(context, 10, 0);
1187 CGContextMoveToPoint(context, 0, 0);
1188 CGContextAddLineToPoint(context, 0, 10);
1189 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1190 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1191 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1192 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1193 CGContextClosePath( context );
1194 CGContextStrokePath(context);
1199 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1200 CGContextScaleCTM( context, 1, -1 );
1203 wxpeer->MacSetCGContextRef( context );
1205 bool handled = wxpeer->MacDoRedraw( 0 );
1206 CGContextRestoreGState( context );
1208 CGContextSaveGState( context );
1212 SEL _cmd = @selector(drawRect:);
1213 wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1214 superimpl(slf, _cmd, *(NSRect*)rect);
1215 CGContextRestoreGState( context );
1216 CGContextSaveGState( context );
1218 // as we called restore above, we have to flip again if necessary
1221 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1222 CGContextScaleCTM( context, 1, -1 );
1224 wxpeer->MacPaintChildrenBorders();
1225 wxpeer->MacSetCGContextRef( NULL );
1226 CGContextRestoreGState( context );
1229 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1231 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1233 wxpeer->OSXHandleClicked(0);
1236 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1240 void wxWidgetCocoaImpl::controlTextDidChange()
1242 wxWindow* wxpeer = (wxWindow*)GetWXPeer();
1245 // since native rtti doesn't have to be enabled and wx' rtti is not aware of the mixin wxTextEntry, workaround is needed
1246 wxTextCtrl *tc = wxDynamicCast( wxpeer , wxTextCtrl );
1247 wxComboBox *cb = wxDynamicCast( wxpeer , wxComboBox );
1249 tc->SendTextUpdatedEventIfAllowed();
1251 cb->SendTextUpdatedEventIfAllowed();
1254 wxFAIL_MSG("Unexpected class for controlTextDidChange event");
1261 #if OBJC_API_VERSION >= 2
1263 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1264 class_addMethod(c, s, i, t );
1268 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1269 { s, (char*) t, i },
1273 void wxOSXCocoaClassAddWXMethods(Class c)
1276 #if OBJC_API_VERSION < 2
1277 static objc_method wxmethods[] =
1281 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1282 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1283 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1285 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1286 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1287 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1289 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1291 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1292 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1293 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1295 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
1297 wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1298 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1299 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1301 wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1302 wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1303 wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1305 wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1307 wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
1309 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1310 wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1311 wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1312 wxOSX_CLASS_ADD_METHOD(c, @selector(resetCursorRects), (IMP) wxOSX_resetCursorRects, "v@:" )
1314 wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1315 wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1317 wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1318 wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1320 #if wxUSE_DRAG_AND_DROP
1321 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1322 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1323 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1324 wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1327 #if OBJC_API_VERSION < 2
1329 static int method_count = WXSIZEOF( wxmethods );
1330 static objc_method_list *wxmethodlist = NULL;
1331 if ( wxmethodlist == NULL )
1333 wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1334 memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1335 wxmethodlist->method_count = method_count;
1336 wxmethodlist->obsolete = 0;
1338 class_addMethods( c, wxmethodlist );
1343 // C++ implementation class
1346 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1348 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl, bool isUserPane ) :
1349 wxWidgetImpl( peer, isRootControl, isUserPane )
1354 // check if the user wants to create the control initially hidden
1355 if ( !peer->IsShown() )
1356 SetVisibility(false);
1358 // gc aware handling
1360 CFRetain(m_osxView);
1361 [m_osxView release];
1364 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1369 void wxWidgetCocoaImpl::Init()
1373 m_lastKeyDownEvent = NULL;
1374 m_hasEditor = false;
1377 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1379 RemoveAssociations( this );
1381 if ( !IsRootControl() )
1383 NSView *sv = [m_osxView superview];
1385 [m_osxView removeFromSuperview];
1387 // gc aware handling
1389 CFRelease(m_osxView);
1392 bool wxWidgetCocoaImpl::IsVisible() const
1394 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1397 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1399 [m_osxView setHidden:(visible ? NO:YES)];
1402 // ----------------------------------------------------------------------------
1403 // window animation stuff
1404 // ----------------------------------------------------------------------------
1406 // define a delegate used to refresh the window during animation
1407 @interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
1413 - (id)init:(wxWindow *)win;
1417 // NSAnimationDelegate methods
1418 - (void)animationDidEnd:(NSAnimation*)animation;
1419 - (void)animation:(NSAnimation*)animation
1420 didReachProgressMark:(NSAnimationProgress)progress;
1423 @implementation wxNSAnimationDelegate
1425 - (id)init:(wxWindow *)win
1440 - (void)animation:(NSAnimation*)animation
1441 didReachProgressMark:(NSAnimationProgress)progress
1443 wxUnusedVar(animation);
1444 wxUnusedVar(progress);
1446 m_win->SendSizeEvent();
1449 - (void)animationDidEnd:(NSAnimation*)animation
1451 wxUnusedVar(animation);
1459 wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1461 wxShowEffect effect,
1464 // create the dictionary describing the animation to perform on this view
1466 viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1467 NSMutableDictionary * const
1468 dict = [NSMutableDictionary dictionaryWithCapacity:4];
1469 [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1471 // determine the start and end rectangles assuming we're hiding the window
1472 const wxRect rectOrig = win->GetRect();
1480 if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1481 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1482 effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1483 else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1484 effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1485 effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1486 else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1487 effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1488 effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1489 else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1490 effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1491 effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1496 case wxSHOW_EFFECT_ROLL_TO_LEFT:
1497 case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1501 case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1502 case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1503 rectEnd.x = rectStart.GetRight();
1507 case wxSHOW_EFFECT_ROLL_TO_TOP:
1508 case wxSHOW_EFFECT_SLIDE_TO_TOP:
1512 case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1513 case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1514 rectEnd.y = rectStart.GetBottom();
1518 case wxSHOW_EFFECT_EXPAND:
1519 rectEnd.x = rectStart.x + rectStart.width / 2;
1520 rectEnd.y = rectStart.y + rectStart.height / 2;
1525 case wxSHOW_EFFECT_BLEND:
1526 [dict setObject:(show ? NSViewAnimationFadeInEffect
1527 : NSViewAnimationFadeOutEffect)
1528 forKey:NSViewAnimationEffectKey];
1531 case wxSHOW_EFFECT_NONE:
1532 case wxSHOW_EFFECT_MAX:
1533 wxFAIL_MSG( "unexpected animation effect" );
1537 wxFAIL_MSG( "unknown animation effect" );
1543 // we need to restore it to the original rectangle instead of making it
1545 wxSwap(rectStart, rectEnd);
1547 // and as the window is currently hidden, we need to show it for the
1548 // animation to be visible at all (but don't restore it at its full
1549 // rectangle as it shouldn't appear immediately)
1550 win->SetSize(rectStart);
1554 NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1555 ? [(NSView *)viewOrWin superview]
1557 const NSRect rStart = wxToNSRect(parentView, rectStart);
1558 const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1560 [dict setObject:[NSValue valueWithRect:rStart]
1561 forKey:NSViewAnimationStartFrameKey];
1562 [dict setObject:[NSValue valueWithRect:rEnd]
1563 forKey:NSViewAnimationEndFrameKey];
1565 // create an animation using the values in the above dictionary
1566 NSViewAnimation * const
1567 anim = [[NSViewAnimation alloc]
1568 initWithViewAnimations:[NSArray arrayWithObject:dict]];
1572 // what is a good default duration? Windows uses 200ms, Web frameworks
1573 // use anything from 250ms to 1s... choose something in the middle
1577 [anim setDuration:timeout/1000.]; // duration is in seconds here
1579 // if the window being animated changes its layout depending on its size
1580 // (which is almost always the case) we need to redo it during animation
1582 // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1583 // controls in wxInfoBar visibly jump around)
1584 const int NUM_LAYOUTS = 20;
1585 for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1586 [anim addProgressMark:f];
1588 wxNSAnimationDelegate * const
1589 animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1590 [anim setDelegate:animDelegate];
1591 [anim startAnimation];
1593 // Cocoa is capable of doing animation asynchronously or even from separate
1594 // thread but wx API doesn't provide any way to be notified about the
1595 // animation end and without this we really must ensure that the window has
1596 // the expected (i.e. the same as if a simple Show() had been used) size
1597 // when we return, so block here until the animation finishes
1599 // notice that because the default animation mode is NSAnimationBlocking,
1600 // no user input events ought to be processed from here
1602 wxEventLoopGuarantor ensureEventLoopExistence;
1603 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1604 while ( ![animDelegate isDone] )
1610 // NSViewAnimation is smart enough to hide the NSView being animated at
1611 // the end but we also must ensure that it's hidden for wx too
1614 // and we must also restore its size because it isn't expected to
1615 // change just because the window was hidden
1616 win->SetSize(rectOrig);
1620 // refresh it once again after the end to ensure that everything is in
1622 win->SendSizeEvent();
1625 [anim setDelegate:nil];
1626 [animDelegate release];
1632 bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
1633 wxShowEffect effect,
1636 return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
1639 void wxWidgetCocoaImpl::Raise()
1644 void wxWidgetCocoaImpl::Lower()
1649 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
1654 // We should do something like this, but it wasn't working in 10.4.
1655 if (GetNeedsDisplay() )
1659 NSRect r = wxToNSRect( [m_osxView superview], *rect );
1660 NSSize offset = NSMakeSize((float)dx, (float)dy);
1661 [m_osxView scrollRect:r by:offset];
1665 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
1667 wxWindowMac* parent = GetWXPeer()->GetParent();
1668 // under Cocoa we might have a contentView in the wxParent to which we have to
1669 // adjust the coordinates
1670 if (parent && [m_osxView superview] != parent->GetHandle() )
1672 int cx = 0,cy = 0,cw = 0,ch = 0;
1673 if ( parent->GetPeer() )
1675 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
1680 [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
1681 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
1682 [m_osxView setFrame:r];
1683 [[m_osxView superview] setNeedsDisplayInRect:r];
1685 wxNSView* wxview = (wxNSView*)m_osxView;
1686 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
1687 if ([wxview respondsToSelector:@selector(updateTrackingArea)] )
1688 [wxview updateTrackingArea];
1690 if ([m_osxView respondsToSelector:@selector(trackingTag)] )
1692 if ( [wxview trackingTag] )
1693 [wxview removeTrackingRect: [wxview trackingTag]];
1695 [wxview setTrackingTag: [wxview addTrackingRect: [m_osxView bounds] owner: wxview userData: nil assumeInside: NO]];
1700 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
1702 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
1706 // under Cocoa we might have a contentView in the wxParent to which we have to
1707 // adjust the coordinates
1708 wxWindowMac* parent = GetWXPeer()->GetParent();
1709 if (parent && [m_osxView superview] != parent->GetHandle() )
1711 int cx = 0,cy = 0,cw = 0,ch = 0;
1712 if ( parent->GetPeer() )
1714 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
1721 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
1723 NSRect rect = [m_osxView frame];
1724 width = (int)rect.size.width;
1725 height = (int)rect.size.height;
1728 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
1730 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
1732 NSView* cv = [m_osxView contentView];
1734 NSRect bounds = [m_osxView bounds];
1735 NSRect rect = [cv frame];
1737 int y = (int)rect.origin.y;
1738 int x = (int)rect.origin.x;
1739 if ( ![ m_osxView isFlipped ] )
1740 y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
1743 width = (int)rect.size.width;
1744 height = (int)rect.size.height;
1749 GetSize( width, height );
1753 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
1756 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
1758 [m_osxView setNeedsDisplay:YES];
1761 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
1763 return [m_osxView needsDisplay];
1766 bool wxWidgetCocoaImpl::CanFocus() const
1768 return [m_osxView canBecomeKeyView] == YES;
1771 bool wxWidgetCocoaImpl::HasFocus() const
1773 return ( FindFocus() == m_osxView );
1776 bool wxWidgetCocoaImpl::SetFocus()
1781 [[m_osxView window] makeKeyAndOrderFront:nil] ;
1782 [[m_osxView window] makeFirstResponder: m_osxView] ;
1787 void wxWidgetCocoaImpl::RemoveFromParent()
1789 [m_osxView removeFromSuperview];
1792 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
1794 NSView* container = parent->GetWXWidget() ;
1795 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
1796 [container addSubview:m_osxView];
1799 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
1801 NSView* targetView = m_osxView;
1802 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
1803 targetView = [(NSScrollView*) m_osxView documentView];
1805 if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
1807 [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
1808 green:(CGFloat) (col.Green() / 255.0)
1809 blue:(CGFloat) (col.Blue() / 255.0)
1810 alpha:(CGFloat) (col.Alpha() / 255.0)]];
1814 bool wxWidgetCocoaImpl::SetBackgroundStyle( wxBackgroundStyle style )
1816 BOOL opaque = ( style == wxBG_STYLE_PAINT );
1818 if ( [m_osxView respondsToSelector:@selector(setOpaque:) ] )
1820 [m_osxView setOpaque: opaque];
1826 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
1828 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
1830 wxCFStringRef cf( title , encoding );
1831 [m_osxView setTitle:cf.AsNSString()];
1833 else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
1835 wxCFStringRef cf( title , encoding );
1836 [m_osxView setStringValue:cf.AsNSString()];
1841 void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
1843 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
1844 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
1845 *pt = wxFromNSPoint( to->GetWXWidget(), p );
1848 wxInt32 wxWidgetCocoaImpl::GetValue() const
1850 return [(NSControl*)m_osxView intValue];
1853 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
1855 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
1857 [m_osxView setIntValue:v];
1859 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
1861 [m_osxView setFloatValue:(double)v];
1863 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
1865 [m_osxView setDoubleValue:(double)v];
1869 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
1871 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
1873 [m_osxView setMinValue:(double)v];
1877 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
1879 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
1881 [m_osxView setMaxValue:(double)v];
1885 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
1887 if ( [m_osxView respondsToSelector:@selector(minValue)] )
1889 return (int)[m_osxView minValue];
1894 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
1896 if ( [m_osxView respondsToSelector:@selector(maxValue)] )
1898 return (int)[m_osxView maxValue];
1903 wxBitmap wxWidgetCocoaImpl::GetBitmap() const
1907 // TODO: how to create a wxBitmap from NSImage?
1909 if ( [m_osxView respondsToSelector:@selector(image:)] )
1910 bmp = [m_osxView image];
1916 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
1918 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
1920 [m_osxView setImage:bitmap.GetNSImage()];
1921 [m_osxView setNeedsDisplay:YES];
1925 void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
1927 if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
1929 NSCellImagePosition pos;
1949 wxFAIL_MSG( "invalid image position" );
1953 [m_osxView setImagePosition:pos];
1957 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
1959 // implementation in subclass
1962 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
1964 r->x = r->y = r->width = r->height = 0;
1966 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
1968 NSRect former = [m_osxView frame];
1969 [m_osxView sizeToFit];
1970 NSRect best = [m_osxView frame];
1971 [m_osxView setFrame:former];
1972 r->width = (int)best.size.width;
1973 r->height = (int)best.size.height;
1977 bool wxWidgetCocoaImpl::IsEnabled() const
1979 NSView* targetView = m_osxView;
1980 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
1981 targetView = [(NSScrollView*) m_osxView documentView];
1983 if ( [targetView respondsToSelector:@selector(isEnabled) ] )
1984 return [targetView isEnabled];
1988 void wxWidgetCocoaImpl::Enable( bool enable )
1990 NSView* targetView = m_osxView;
1991 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
1992 targetView = [(NSScrollView*) m_osxView documentView];
1994 if ( [targetView respondsToSelector:@selector(setEnabled:) ] )
1995 [targetView setEnabled:enable];
1998 void wxWidgetCocoaImpl::PulseGauge()
2002 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
2006 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
2008 NSControlSize size = NSRegularControlSize;
2012 case wxWINDOW_VARIANT_NORMAL :
2013 size = NSRegularControlSize;
2016 case wxWINDOW_VARIANT_SMALL :
2017 size = NSSmallControlSize;
2020 case wxWINDOW_VARIANT_MINI :
2021 size = NSMiniControlSize;
2024 case wxWINDOW_VARIANT_LARGE :
2025 size = NSRegularControlSize;
2029 wxFAIL_MSG(wxT("unexpected window variant"));
2032 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
2033 [m_osxView setControlSize:size];
2034 else if ([m_osxView respondsToSelector:@selector(cell)])
2036 id cell = [(id)m_osxView cell];
2037 if ([cell respondsToSelector:@selector(setControlSize:)])
2038 [cell setControlSize:size];
2042 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&col, long, bool)
2044 if ([m_osxView respondsToSelector:@selector(setFont:)])
2045 [m_osxView setFont: font.OSXGetNSFont()];
2046 if ([m_osxView respondsToSelector:@selector(setTextColor:)])
2047 [m_osxView setTextColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2048 green:(CGFloat) (col.Green() / 255.0)
2049 blue:(CGFloat) (col.Blue() / 255.0)
2050 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2053 void wxWidgetCocoaImpl::SetToolTip(wxToolTip* tooltip)
2057 wxCFStringRef cf( tooltip->GetTip() , m_wxPeer->GetFont().GetEncoding() );
2058 [m_osxView setToolTip: cf.AsNSString()];
2061 [m_osxView setToolTip: nil];
2065 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
2067 WXWidget c = control ? control : (WXWidget) m_osxView;
2068 wxWidgetImpl::Associate( c, this ) ;
2069 if ([c respondsToSelector:@selector(setAction:)])
2072 [c setAction: @selector(controlAction:)];
2073 if ([c respondsToSelector:@selector(setDoubleAction:)])
2075 [c setDoubleAction: @selector(controlDoubleAction:)];
2081 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
2083 wxKeyEvent wxevent(wxEVT_CHAR);
2084 SetupKeyEvent( wxevent, event, text );
2086 return GetWXPeer()->OSXHandleKeyEvent(wxevent);
2089 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
2091 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
2092 SetupKeyEvent( wxevent, event );
2093 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
2095 // this will fire higher level events, like insertText, to help
2096 // us handle EVT_CHAR, etc.
2100 if ( IsUserPane() && [event type] == NSKeyDown)
2102 if ( wxevent.GetKeyCode() < WXK_SPACE || wxevent.GetKeyCode() == WXK_DELETE || wxevent.GetKeyCode() >= WXK_START )
2104 // eventually we could setup a doCommandBySelector catcher and retransform this into the wx key chars
2105 wxKeyEvent wxevent2(wxevent) ;
2106 wxevent2.SetEventType(wxEVT_CHAR);
2107 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2111 if ( !wxevent.CmdDown() )
2113 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2114 [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
2116 [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
2126 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
2128 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
2129 SetupMouseEvent(wxevent , event) ;
2131 return GetWXPeer()->HandleWindowEvent(wxevent);
2134 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
2136 wxWindow* thisWindow = GetWXPeer();
2137 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
2139 thisWindow->MacInvalidateBorders();
2142 if ( receivedFocus )
2144 wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
2145 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
2146 thisWindow->HandleWindowEvent(eventFocus);
2149 if ( thisWindow->GetCaret() )
2150 thisWindow->GetCaret()->OnSetFocus();
2153 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
2154 event.SetEventObject(thisWindow);
2156 event.SetWindow(otherWindow->GetWXPeer());
2157 thisWindow->HandleWindowEvent(event) ;
2159 else // !receivedFocuss
2162 if ( thisWindow->GetCaret() )
2163 thisWindow->GetCaret()->OnKillFocus();
2166 wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
2168 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
2169 event.SetEventObject(thisWindow);
2171 event.SetWindow(otherWindow->GetWXPeer());
2172 thisWindow->HandleWindowEvent(event) ;
2176 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
2180 NSPoint location = [NSEvent mouseLocation];
2181 location = [[m_osxView window] convertScreenToBase:location];
2182 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
2184 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
2186 [(NSCursor*)cursor.GetHCURSOR() set];
2189 [[m_osxView window] invalidateCursorRectsForView:m_osxView];
2192 void wxWidgetCocoaImpl::CaptureMouse()
2194 [[m_osxView window] disableCursorRects];
2197 void wxWidgetCocoaImpl::ReleaseMouse()
2199 [[m_osxView window] enableCursorRects];
2202 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
2204 m_isFlipped = flipped;
2211 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
2212 wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
2213 long WXUNUSED(style), long WXUNUSED(extraStyle))
2215 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
2216 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
2218 // temporary hook for dnd
2219 [v registerForDraggedTypes:[NSArray arrayWithObjects:
2220 NSStringPboardType, NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSPDFPboardType, nil]];
2222 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v, false, true );
2226 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
2228 NSWindow* tlw = now->GetWXWindow();
2230 wxWidgetCocoaImpl* c = NULL;
2231 if ( now->IsNativeWindowWrapper() )
2233 NSView* cv = [tlw contentView];
2234 c = new wxWidgetCocoaImpl( now, cv, true );
2235 // increase ref count, because the impl destructor will decrement it again
2237 if ( !now->IsShown() )
2243 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2244 c = new wxWidgetCocoaImpl( now, v, true );
2245 c->InstallEventHandler();
2246 [tlw setContentView:v];