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, int eventType )
144 if ([event type] != NSFlagsChanged)
146 NSString* s = [event charactersIgnoringModifiers];
147 // backspace char reports as delete w/modifiers for some reason
150 if ( eventType == wxEVT_CHAR && ([event modifierFlags] & NSControlKeyMask) && ( [s characterAtIndex:0] >= 'a' && [s characterAtIndex:0] <= 'z' ) )
152 retval = WXK_CONTROL_A + ([s characterAtIndex:0] - 'a');
156 switch ( [s characterAtIndex:0] )
163 case NSUpArrowFunctionKey :
166 case NSDownArrowFunctionKey :
169 case NSLeftArrowFunctionKey :
172 case NSRightArrowFunctionKey :
175 case NSInsertFunctionKey :
178 case NSDeleteFunctionKey :
181 case NSHomeFunctionKey :
184 // case NSBeginFunctionKey :
185 // retval = WXK_BEGIN;
187 case NSEndFunctionKey :
190 case NSPageUpFunctionKey :
193 case NSPageDownFunctionKey :
194 retval = WXK_PAGEDOWN;
196 case NSHelpFunctionKey :
200 int intchar = [s characterAtIndex: 0];
201 if ( intchar >= NSF1FunctionKey && intchar <= NSF24FunctionKey )
202 retval = WXK_F1 + (intchar - NSF1FunctionKey );
209 // Some keys don't seem to have constants. The code mimics the approach
210 // taken by WebKit. See:
211 // http://trac.webkit.org/browser/trunk/WebCore/platform/mac/KeyEventMac.mm
212 switch( [event keyCode] )
217 retval = WXK_CONTROL;
221 retval = WXK_CAPITAL;
224 case 56: // Left Shift
225 case 60: // Right Shift
230 case 61: // Right Alt
234 case 59: // Left Ctrl
235 case 62: // Right Ctrl
236 retval = WXK_RAW_CONTROL;
248 retval = WXK_NUMPAD_DIVIDE;
251 retval = WXK_NUMPAD_MULTIPLY;
254 retval = WXK_NUMPAD_SUBTRACT;
257 retval = WXK_NUMPAD_ADD;
260 retval = WXK_NUMPAD_ENTER;
263 retval = WXK_NUMPAD_DECIMAL;
266 retval = WXK_NUMPAD0;
269 retval = WXK_NUMPAD1;
272 retval = WXK_NUMPAD2;
275 retval = WXK_NUMPAD3;
278 retval = WXK_NUMPAD4;
281 retval = WXK_NUMPAD5;
284 retval = WXK_NUMPAD6;
287 retval = WXK_NUMPAD7;
290 retval = WXK_NUMPAD8;
293 retval = WXK_NUMPAD9;
296 //retval = [event keyCode];
302 void wxWidgetCocoaImpl::SetupKeyEvent(wxKeyEvent &wxevent , NSEvent * nsEvent, NSString* charString)
304 UInt32 modifiers = [nsEvent modifierFlags] ;
305 int eventType = [nsEvent type];
307 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
308 wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
309 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
310 wxevent.m_controlDown = modifiers & NSCommandKeyMask;
312 wxevent.m_rawCode = [nsEvent keyCode];
313 wxevent.m_rawFlags = modifiers;
315 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
318 if ( eventType != NSFlagsChanged )
320 NSString* nschars = [[nsEvent charactersIgnoringModifiers] uppercaseString];
323 // if charString is set, it did not come from key up / key down
324 wxevent.SetEventType( wxEVT_CHAR );
325 chars = wxCFStringRef::AsString(charString);
329 chars = wxCFStringRef::AsString(nschars);
333 int aunichar = chars.Length() > 0 ? chars[0] : 0;
336 if (wxevent.GetEventType() != wxEVT_CHAR)
338 keyval = wxOSXTranslateCocoaKey(nsEvent, wxevent.GetEventType()) ;
342 wxevent.SetEventType( wxEVT_KEY_DOWN ) ;
345 wxevent.SetEventType( wxEVT_KEY_UP ) ;
347 case NSFlagsChanged :
351 wxevent.SetEventType( wxevent.m_controlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
354 wxevent.SetEventType( wxevent.m_shiftDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
357 wxevent.SetEventType( wxevent.m_altDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
359 case WXK_RAW_CONTROL:
360 wxevent.SetEventType( wxevent.m_rawControlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
371 if ( wxevent.GetEventType() == wxEVT_KEY_UP || wxevent.GetEventType() == wxEVT_KEY_DOWN )
372 keyval = wxToupper( aunichar ) ;
378 // OS X generates events with key codes in Unicode private use area for
379 // unprintable symbols such as cursor arrows (WXK_UP is mapped to U+F700)
380 // and function keys (WXK_F2 is U+F705). We don't want to use them as the
381 // result of wxKeyEvent::GetUnicodeKey() however as it's supposed to return
382 // WXK_NONE for "non characters" so explicitly exclude them.
384 // We only exclude the private use area inside the Basic Multilingual Plane
385 // as key codes beyond it don't seem to be currently used.
386 if ( !(aunichar >= 0xe000 && aunichar < 0xf900) )
387 wxevent.m_uniChar = aunichar;
389 wxevent.m_keyCode = keyval;
391 wxWindowMac* peer = GetWXPeer();
394 wxevent.SetEventObject(peer);
395 wxevent.SetId(peer->GetId()) ;
399 UInt32 g_lastButton = 0 ;
400 bool g_lastButtonWasFakeRight = false ;
402 // better scroll wheel support
403 // see http://lists.apple.com/archives/cocoa-dev/2007/Feb/msg00050.html
405 @interface NSEvent (DeviceDelta)
406 - (CGFloat)deviceDeltaX;
407 - (CGFloat)deviceDeltaY;
410 void wxWidgetCocoaImpl::SetupMouseEvent( wxMouseEvent &wxevent , NSEvent * nsEvent )
412 int eventType = [nsEvent type];
413 UInt32 modifiers = [nsEvent modifierFlags] ;
415 NSPoint locationInWindow = [nsEvent locationInWindow];
417 // adjust coordinates for the window of the target view
418 if ( [nsEvent window] != [m_osxView window] )
420 if ( [nsEvent window] != nil )
421 locationInWindow = [[nsEvent window] convertBaseToScreen:locationInWindow];
423 if ( [m_osxView window] != nil )
424 locationInWindow = [[m_osxView window] convertScreenToBase:locationInWindow];
427 NSPoint locationInView = [m_osxView convertPoint:locationInWindow fromView:nil];
428 wxPoint locationInViewWX = wxFromNSPoint( m_osxView, locationInView );
430 // these parameters are not given for all events
431 UInt32 button = [nsEvent buttonNumber];
432 UInt32 clickCount = 0;
434 wxevent.m_x = locationInViewWX.x;
435 wxevent.m_y = locationInViewWX.y;
436 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
437 wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
438 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
439 wxevent.m_controlDown = modifiers & NSCommandKeyMask;
440 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
442 UInt32 mouseChord = 0;
446 case NSLeftMouseDown :
447 case NSLeftMouseDragged :
450 case NSRightMouseDown :
451 case NSRightMouseDragged :
454 case NSOtherMouseDown :
455 case NSOtherMouseDragged :
460 // a control click is interpreted as a right click
461 bool thisButtonIsFakeRight = false ;
462 if ( button == 0 && (modifiers & NSControlKeyMask) )
465 thisButtonIsFakeRight = true ;
468 // otherwise we report double clicks by connecting a left click with a ctrl-left click
469 if ( clickCount > 1 && button != g_lastButton )
472 // we must make sure that our synthetic 'right' button corresponds in
473 // mouse down, moved and mouse up, and does not deliver a right down and left up
476 case NSLeftMouseDown :
477 case NSRightMouseDown :
478 case NSOtherMouseDown :
479 g_lastButton = button ;
480 g_lastButtonWasFakeRight = thisButtonIsFakeRight ;
487 g_lastButtonWasFakeRight = false ;
489 else if ( g_lastButton == 1 && g_lastButtonWasFakeRight )
490 button = g_lastButton ;
492 // Adjust the chord mask to remove the primary button and add the
493 // secondary button. It is possible that the secondary button is
494 // already pressed, e.g. on a mouse connected to a laptop, but this
495 // possibility is ignored here:
496 if( thisButtonIsFakeRight && ( mouseChord & 1U ) )
497 mouseChord = ((mouseChord & ~1U) | 2U);
500 wxevent.m_leftDown = true ;
502 wxevent.m_rightDown = true ;
504 wxevent.m_middleDown = true ;
506 // translate into wx types
509 case NSLeftMouseDown :
510 case NSRightMouseDown :
511 case NSOtherMouseDown :
512 clickCount = [nsEvent clickCount];
516 wxevent.SetEventType( clickCount > 1 ? wxEVT_LEFT_DCLICK : wxEVT_LEFT_DOWN ) ;
520 wxevent.SetEventType( clickCount > 1 ? wxEVT_RIGHT_DCLICK : wxEVT_RIGHT_DOWN ) ;
524 wxevent.SetEventType( clickCount > 1 ? wxEVT_MIDDLE_DCLICK : wxEVT_MIDDLE_DOWN ) ;
533 case NSRightMouseUp :
534 case NSOtherMouseUp :
535 clickCount = [nsEvent clickCount];
539 wxevent.SetEventType( wxEVT_LEFT_UP ) ;
543 wxevent.SetEventType( wxEVT_RIGHT_UP ) ;
547 wxevent.SetEventType( wxEVT_MIDDLE_UP ) ;
560 wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ;
562 // see http://developer.apple.com/qa/qa2005/qa1453.html
563 // for more details on why we have to look for the exact type
565 const EventRef cEvent = (EventRef) [nsEvent eventRef];
566 bool isMouseScrollEvent = false;
568 isMouseScrollEvent = ::GetEventKind(cEvent) == kEventMouseScroll;
570 if ( isMouseScrollEvent )
572 deltaX = [nsEvent deviceDeltaX];
573 deltaY = [nsEvent deviceDeltaY];
577 deltaX = ([nsEvent deltaX] * 10);
578 deltaY = ([nsEvent deltaY] * 10);
581 wxevent.m_wheelDelta = 10;
582 wxevent.m_linesPerAction = 1;
584 if ( fabs(deltaX) > fabs(deltaY) )
586 wxevent.m_wheelAxis = 1;
587 wxevent.m_wheelRotation = (int)deltaX;
591 wxevent.m_wheelRotation = (int)deltaY;
597 case NSMouseEntered :
598 wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
601 wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
603 case NSLeftMouseDragged :
604 case NSRightMouseDragged :
605 case NSOtherMouseDragged :
607 wxevent.SetEventType( wxEVT_MOTION ) ;
613 wxevent.m_clickCount = clickCount;
614 wxWindowMac* peer = GetWXPeer();
617 wxevent.SetEventObject(peer);
618 wxevent.SetId(peer->GetId()) ;
622 @implementation wxNSView
626 static BOOL initialized = NO;
630 wxOSXCocoaClassAddWXMethods( self );
634 - (void) setTrackingTag: (NSTrackingRectTag)tag
639 - (NSTrackingRectTag) trackingTag
644 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
645 - (void) updateTrackingArea
649 [self removeTrackingArea: _trackingArea];
650 [_trackingArea release];
653 NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingMouseMoved|NSTrackingActiveAlways;
655 NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: [self bounds] options: options owner: self userInfo: nil];
656 [self addTrackingArea: area];
658 _trackingArea = area;
661 - (NSTrackingArea*) trackingArea
663 return _trackingArea;
672 #if wxUSE_DRAG_AND_DROP
674 // see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
675 // for details on the NSPasteboard -> PasteboardRef conversion
677 NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
679 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
681 return NSDragOperationNone;
683 return impl->draggingEntered(sender, self, _cmd);
686 void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
688 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
692 return impl->draggingExited(sender, self, _cmd);
695 NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
697 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
699 return NSDragOperationNone;
701 return impl->draggingUpdated(sender, self, _cmd);
704 BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
706 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
708 return NSDragOperationNone;
710 return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
715 void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
717 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
721 impl->mouseEvent(event, self, _cmd);
724 BOOL wxOSX_acceptsFirstMouse(NSView* WXUNUSED(self), SEL WXUNUSED(_cmd), NSEvent *WXUNUSED(event))
726 // This is needed to support click through, otherwise the first click on a window
727 // will not do anything unless it is the active window already.
731 void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
733 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
737 impl->keyEvent(event, self, _cmd);
740 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
742 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
746 impl->insertText(text, self, _cmd);
749 BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
751 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
755 return impl->performKeyEquivalent(event, self, _cmd);
758 BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
760 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
764 return impl->acceptsFirstResponder(self, _cmd);
767 BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
769 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
773 return impl->becomeFirstResponder(self, _cmd);
776 BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
778 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
782 return impl->resignFirstResponder(self, _cmd);
785 void wxOSX_resetCursorRects(NSView* self, SEL _cmd)
787 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
791 impl->resetCursorRects(self, _cmd);
794 BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
796 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
800 return impl->isFlipped(self, _cmd) ? YES:NO;
803 typedef void (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
805 void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
807 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
812 // OS X starts a NSUIHeartBeatThread for animating the default button in a
813 // dialog. This causes a drawRect of the active dialog from outside the
814 // main UI thread. This causes an occasional crash since the wx drawing
815 // objects (like wxPen) are not thread safe.
817 // Notice that NSUIHeartBeatThread seems to be undocumented and doing
818 // [NSWindow setAllowsConcurrentViewDrawing:NO] does not affect it.
819 if ( !wxThread::IsMain() )
821 if ( impl->IsUserPane() )
823 wxWindow* win = impl->GetWXPeer();
824 if ( win->UseBgCol() )
827 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
828 CGContextSaveGState( context );
830 CGContextSetFillColorWithColor( context, win->GetBackgroundColour().GetCGColor());
831 CGRect r = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
832 CGContextFillRect( context, r );
834 CGContextRestoreGState( context );
839 // just call the superclass handler, we don't need any custom wx drawing
840 // here and it seems to work fine:
841 wxOSX_DrawRectHandlerPtr
842 superimpl = (wxOSX_DrawRectHandlerPtr)
843 [[self superclass] instanceMethodForSelector:_cmd];
844 superimpl(self, _cmd, rect);
849 #endif // wxUSE_THREADS
851 return impl->drawRect(&rect, self, _cmd);
854 void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
856 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
860 impl->controlAction(self, _cmd, sender);
863 void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
865 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
869 impl->controlDoubleAction(self, _cmd, sender);
872 unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
874 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
875 NSPasteboard *pboard = [sender draggingPasteboard];
876 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
878 wxWindow* wxpeer = GetWXPeer();
879 if ( wxpeer == NULL )
880 return NSDragOperationNone;
882 wxDropTarget* target = wxpeer->GetDropTarget();
883 if ( target == NULL )
884 return NSDragOperationNone;
886 wxDragResult result = wxDragNone;
887 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
888 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
890 if ( sourceDragMask & NSDragOperationLink )
892 else if ( sourceDragMask & NSDragOperationCopy )
894 else if ( sourceDragMask & NSDragOperationMove )
897 PasteboardRef pboardRef;
898 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
899 target->SetCurrentDragPasteboard(pboardRef);
900 result = target->OnEnter(pt.x, pt.y, result);
901 CFRelease(pboardRef);
903 NSDragOperation nsresult = NSDragOperationNone;
907 nsresult = NSDragOperationLink;
909 nsresult = NSDragOperationMove;
911 nsresult = NSDragOperationCopy;
918 void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
920 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
921 NSPasteboard *pboard = [sender draggingPasteboard];
923 wxWindow* wxpeer = GetWXPeer();
924 if ( wxpeer == NULL )
927 wxDropTarget* target = wxpeer->GetDropTarget();
928 if ( target == NULL )
931 PasteboardRef pboardRef;
932 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
933 target->SetCurrentDragPasteboard(pboardRef);
935 CFRelease(pboardRef);
938 unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
940 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
941 NSPasteboard *pboard = [sender draggingPasteboard];
942 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
944 wxWindow* wxpeer = GetWXPeer();
945 if ( wxpeer == NULL )
946 return NSDragOperationNone;
948 wxDropTarget* target = wxpeer->GetDropTarget();
949 if ( target == NULL )
950 return NSDragOperationNone;
952 wxDragResult result = wxDragNone;
953 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
954 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
956 if ( sourceDragMask & NSDragOperationLink )
958 else if ( sourceDragMask & NSDragOperationCopy )
960 else if ( sourceDragMask & NSDragOperationMove )
963 PasteboardRef pboardRef;
964 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
965 target->SetCurrentDragPasteboard(pboardRef);
966 result = target->OnDragOver(pt.x, pt.y, result);
967 CFRelease(pboardRef);
969 NSDragOperation nsresult = NSDragOperationNone;
973 nsresult = NSDragOperationLink;
975 nsresult = NSDragOperationMove;
977 nsresult = NSDragOperationCopy;
984 bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
986 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
988 NSPasteboard *pboard = [sender draggingPasteboard];
989 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
991 wxWindow* wxpeer = GetWXPeer();
992 wxDropTarget* target = wxpeer->GetDropTarget();
993 wxDragResult result = wxDragNone;
994 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
995 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
997 if ( sourceDragMask & NSDragOperationLink )
999 else if ( sourceDragMask & NSDragOperationCopy )
1000 result = wxDragCopy;
1001 else if ( sourceDragMask & NSDragOperationMove )
1002 result = wxDragMove;
1004 PasteboardRef pboardRef;
1005 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1006 target->SetCurrentDragPasteboard(pboardRef);
1008 if (target->OnDrop(pt.x, pt.y))
1009 result = target->OnData(pt.x, pt.y, result);
1011 CFRelease(pboardRef);
1013 return result != wxDragNone;
1016 typedef void (*wxOSX_TextEventHandlerPtr)(NSView* self, SEL _cmd, NSString *event);
1017 typedef void (*wxOSX_EventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
1018 typedef BOOL (*wxOSX_PerformKeyEventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
1019 typedef BOOL (*wxOSX_FocusHandlerPtr)(NSView* self, SEL _cmd);
1020 typedef BOOL (*wxOSX_ResetCursorRectsHandlerPtr)(NSView* self, SEL _cmd);
1022 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1024 if ( !DoHandleMouseEvent(event) )
1026 // for plain NSView mouse events would propagate to parents otherwise
1029 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1030 superimpl(slf, (SEL)_cmd, event);
1035 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1037 if ( [event type] == NSKeyDown )
1039 // there are key equivalents that are not command-combos and therefore not handled by cocoa automatically,
1040 // therefore we call the menubar directly here, exit if the menu is handling the shortcut
1041 if ( [[[NSApplication sharedApplication] mainMenu] performKeyEquivalent:event] )
1044 m_lastKeyDownEvent = event;
1047 if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
1049 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1050 superimpl(slf, (SEL)_cmd, event);
1052 m_lastKeyDownEvent = NULL;
1055 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
1057 if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
1059 wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1060 superimpl(slf, (SEL)_cmd, text);
1065 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
1067 bool handled = false;
1069 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1070 SetupKeyEvent( wxevent, event );
1072 // because performKeyEquivalent is going up the entire view hierarchy, we don't have to
1073 // walk up the ancestors ourselves but let cocoa do it
1075 int command = m_wxPeer->GetAcceleratorTable()->GetCommand( wxevent );
1078 wxEvtHandler * const handler = m_wxPeer->GetEventHandler();
1080 wxCommandEvent command_event( wxEVT_COMMAND_MENU_SELECTED, command );
1081 handled = handler->ProcessEvent( command_event );
1085 // accelerators can also be used with buttons, try them too
1086 command_event.SetEventType(wxEVT_COMMAND_BUTTON_CLICKED);
1087 handled = handler->ProcessEvent( command_event );
1093 wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1094 return superimpl(slf, (SEL)_cmd, event);
1099 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
1102 return m_wxPeer->AcceptsFocus();
1105 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1106 return superimpl(slf, (SEL)_cmd);
1110 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
1112 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1113 // get the current focus before running becomeFirstResponder
1114 NSView* otherView = FindFocus();
1116 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1117 BOOL r = superimpl(slf, (SEL)_cmd);
1120 DoNotifyFocusEvent( true, otherWindow );
1126 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
1128 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1129 BOOL r = superimpl(slf, (SEL)_cmd);
1130 // get the current focus after running resignFirstResponder
1131 // note that this value isn't reliable, it might return the same view that
1133 NSView* otherView = FindFocus();
1134 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1136 // It doesn't make sense to notify about the loss of focus if we're not
1137 // really losing it and the window which has just gained focus is the same
1138 // one as this window itself. Of course, this should never happen in the
1139 // first place but somehow it does in wxGrid code and without this check we
1140 // enter into an infinite recursion, see #12267.
1141 if ( otherWindow == this )
1144 // NSTextViews have an editor as true responder, therefore the might get the
1145 // resign notification if their editor takes over, don't trigger any event then
1146 if ( r && !m_hasEditor)
1148 DoNotifyFocusEvent( false, otherWindow );
1153 void wxWidgetCocoaImpl::resetCursorRects(WXWidget slf, void *_cmd)
1155 wxWindow* wxpeer = GetWXPeer();
1158 NSCursor *cursor = (NSCursor*)wxpeer->GetCursor().GetHCURSOR();
1161 wxOSX_ResetCursorRectsHandlerPtr superimpl = (wxOSX_ResetCursorRectsHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1162 superimpl(slf, (SEL)_cmd);
1166 [slf addCursorRect: [slf bounds]
1172 bool wxWidgetCocoaImpl::isFlipped(WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1178 #define OSX_DEBUG_DRAWING 0
1180 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
1182 // preparing the update region
1185 const NSRect *rects;
1188 [slf getRectsBeingDrawn:&rects count:&count];
1189 for ( int i = 0 ; i < count ; ++i )
1191 updateRgn.Union(wxFromNSRect(slf, rects[i]));
1194 wxWindow* wxpeer = GetWXPeer();
1196 if ( wxpeer->MacGetLeftBorderSize() != 0 || wxpeer->MacGetTopBorderSize() != 0 )
1198 // as this update region is in native window locals we must adapt it to wx window local
1199 updateRgn.Offset( wxpeer->MacGetLeftBorderSize() , wxpeer->MacGetTopBorderSize() );
1202 if ( wxpeer->MacGetTopLevelWindow()->GetWindowStyle() & wxFRAME_SHAPED )
1204 int xoffset = 0, yoffset = 0;
1205 wxRegion rgn = wxpeer->MacGetTopLevelWindow()->GetShape();
1206 wxpeer->MacRootWindowToWindow( &xoffset, &yoffset );
1207 rgn.Offset( xoffset, yoffset );
1208 updateRgn.Intersect(rgn);
1211 wxpeer->GetUpdateRegion() = updateRgn;
1213 // setting up the drawing context
1215 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1216 CGContextSaveGState( context );
1218 #if OSX_DEBUG_DRAWING
1219 CGContextBeginPath( context );
1220 CGContextMoveToPoint(context, 0, 0);
1221 NSRect bounds = [slf bounds];
1222 CGContextAddLineToPoint(context, 10, 0);
1223 CGContextMoveToPoint(context, 0, 0);
1224 CGContextAddLineToPoint(context, 0, 10);
1225 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1226 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1227 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1228 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1229 CGContextClosePath( context );
1230 CGContextStrokePath(context);
1235 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1236 CGContextScaleCTM( context, 1, -1 );
1239 wxpeer->MacSetCGContextRef( context );
1241 bool handled = wxpeer->MacDoRedraw( 0 );
1242 CGContextRestoreGState( context );
1244 CGContextSaveGState( context );
1248 SEL _cmd = @selector(drawRect:);
1249 wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1250 superimpl(slf, _cmd, *(NSRect*)rect);
1251 CGContextRestoreGState( context );
1252 CGContextSaveGState( context );
1254 // as we called restore above, we have to flip again if necessary
1257 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1258 CGContextScaleCTM( context, 1, -1 );
1260 wxpeer->MacPaintChildrenBorders();
1261 wxpeer->MacSetCGContextRef( NULL );
1262 CGContextRestoreGState( context );
1265 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1267 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1269 wxpeer->OSXHandleClicked(0);
1272 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1276 void wxWidgetCocoaImpl::controlTextDidChange()
1278 wxWindow* wxpeer = (wxWindow*)GetWXPeer();
1281 // since native rtti doesn't have to be enabled and wx' rtti is not aware of the mixin wxTextEntry, workaround is needed
1282 wxTextCtrl *tc = wxDynamicCast( wxpeer , wxTextCtrl );
1283 wxComboBox *cb = wxDynamicCast( wxpeer , wxComboBox );
1285 tc->SendTextUpdatedEventIfAllowed();
1287 cb->SendTextUpdatedEventIfAllowed();
1290 wxFAIL_MSG("Unexpected class for controlTextDidChange event");
1297 #if OBJC_API_VERSION >= 2
1299 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1300 class_addMethod(c, s, i, t );
1304 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1305 { s, (char*) t, i },
1309 void wxOSXCocoaClassAddWXMethods(Class c)
1312 #if OBJC_API_VERSION < 2
1313 static objc_method wxmethods[] =
1317 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1318 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1319 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1321 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1322 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1323 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1325 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1327 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1328 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1329 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1331 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
1333 wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1334 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1335 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1337 wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1338 wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1339 wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1341 wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1343 wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
1345 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1346 wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1347 wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1348 wxOSX_CLASS_ADD_METHOD(c, @selector(resetCursorRects), (IMP) wxOSX_resetCursorRects, "v@:" )
1350 wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1351 wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1353 wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1354 wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1356 #if wxUSE_DRAG_AND_DROP
1357 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1358 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1359 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1360 wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1363 #if OBJC_API_VERSION < 2
1365 static int method_count = WXSIZEOF( wxmethods );
1366 static objc_method_list *wxmethodlist = NULL;
1367 if ( wxmethodlist == NULL )
1369 wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1370 memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1371 wxmethodlist->method_count = method_count;
1372 wxmethodlist->obsolete = 0;
1374 class_addMethods( c, wxmethodlist );
1379 // C++ implementation class
1382 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1384 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl, bool isUserPane ) :
1385 wxWidgetImpl( peer, isRootControl, isUserPane )
1390 // check if the user wants to create the control initially hidden
1391 if ( !peer->IsShown() )
1392 SetVisibility(false);
1394 // gc aware handling
1396 CFRetain(m_osxView);
1397 [m_osxView release];
1400 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1405 void wxWidgetCocoaImpl::Init()
1409 m_lastKeyDownEvent = NULL;
1410 m_hasEditor = false;
1413 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1415 RemoveAssociations( this );
1417 if ( !IsRootControl() )
1419 NSView *sv = [m_osxView superview];
1421 [m_osxView removeFromSuperview];
1423 // gc aware handling
1425 CFRelease(m_osxView);
1428 bool wxWidgetCocoaImpl::IsVisible() const
1430 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1433 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1435 [m_osxView setHidden:(visible ? NO:YES)];
1438 // ----------------------------------------------------------------------------
1439 // window animation stuff
1440 // ----------------------------------------------------------------------------
1442 // define a delegate used to refresh the window during animation
1443 @interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
1449 - (id)init:(wxWindow *)win;
1453 // NSAnimationDelegate methods
1454 - (void)animationDidEnd:(NSAnimation*)animation;
1455 - (void)animation:(NSAnimation*)animation
1456 didReachProgressMark:(NSAnimationProgress)progress;
1459 @implementation wxNSAnimationDelegate
1461 - (id)init:(wxWindow *)win
1463 self = [super init];
1476 - (void)animation:(NSAnimation*)animation
1477 didReachProgressMark:(NSAnimationProgress)progress
1479 wxUnusedVar(animation);
1480 wxUnusedVar(progress);
1482 m_win->SendSizeEvent();
1485 - (void)animationDidEnd:(NSAnimation*)animation
1487 wxUnusedVar(animation);
1495 wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1497 wxShowEffect effect,
1500 // create the dictionary describing the animation to perform on this view
1502 viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1503 NSMutableDictionary * const
1504 dict = [NSMutableDictionary dictionaryWithCapacity:4];
1505 [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1507 // determine the start and end rectangles assuming we're hiding the window
1508 const wxRect rectOrig = win->GetRect();
1516 if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1517 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1518 effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1519 else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1520 effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1521 effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1522 else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1523 effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1524 effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1525 else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1526 effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1527 effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1532 case wxSHOW_EFFECT_ROLL_TO_LEFT:
1533 case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1537 case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1538 case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1539 rectEnd.x = rectStart.GetRight();
1543 case wxSHOW_EFFECT_ROLL_TO_TOP:
1544 case wxSHOW_EFFECT_SLIDE_TO_TOP:
1548 case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1549 case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1550 rectEnd.y = rectStart.GetBottom();
1554 case wxSHOW_EFFECT_EXPAND:
1555 rectEnd.x = rectStart.x + rectStart.width / 2;
1556 rectEnd.y = rectStart.y + rectStart.height / 2;
1561 case wxSHOW_EFFECT_BLEND:
1562 [dict setObject:(show ? NSViewAnimationFadeInEffect
1563 : NSViewAnimationFadeOutEffect)
1564 forKey:NSViewAnimationEffectKey];
1567 case wxSHOW_EFFECT_NONE:
1568 case wxSHOW_EFFECT_MAX:
1569 wxFAIL_MSG( "unexpected animation effect" );
1573 wxFAIL_MSG( "unknown animation effect" );
1579 // we need to restore it to the original rectangle instead of making it
1581 wxSwap(rectStart, rectEnd);
1583 // and as the window is currently hidden, we need to show it for the
1584 // animation to be visible at all (but don't restore it at its full
1585 // rectangle as it shouldn't appear immediately)
1586 win->SetSize(rectStart);
1590 NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1591 ? [(NSView *)viewOrWin superview]
1593 const NSRect rStart = wxToNSRect(parentView, rectStart);
1594 const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1596 [dict setObject:[NSValue valueWithRect:rStart]
1597 forKey:NSViewAnimationStartFrameKey];
1598 [dict setObject:[NSValue valueWithRect:rEnd]
1599 forKey:NSViewAnimationEndFrameKey];
1601 // create an animation using the values in the above dictionary
1602 NSViewAnimation * const
1603 anim = [[NSViewAnimation alloc]
1604 initWithViewAnimations:[NSArray arrayWithObject:dict]];
1608 // what is a good default duration? Windows uses 200ms, Web frameworks
1609 // use anything from 250ms to 1s... choose something in the middle
1613 [anim setDuration:timeout/1000.]; // duration is in seconds here
1615 // if the window being animated changes its layout depending on its size
1616 // (which is almost always the case) we need to redo it during animation
1618 // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1619 // controls in wxInfoBar visibly jump around)
1620 const int NUM_LAYOUTS = 20;
1621 for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1622 [anim addProgressMark:f];
1624 wxNSAnimationDelegate * const
1625 animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1626 [anim setDelegate:animDelegate];
1627 [anim startAnimation];
1629 // Cocoa is capable of doing animation asynchronously or even from separate
1630 // thread but wx API doesn't provide any way to be notified about the
1631 // animation end and without this we really must ensure that the window has
1632 // the expected (i.e. the same as if a simple Show() had been used) size
1633 // when we return, so block here until the animation finishes
1635 // notice that because the default animation mode is NSAnimationBlocking,
1636 // no user input events ought to be processed from here
1638 wxEventLoopGuarantor ensureEventLoopExistence;
1639 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1640 while ( ![animDelegate isDone] )
1646 // NSViewAnimation is smart enough to hide the NSView being animated at
1647 // the end but we also must ensure that it's hidden for wx too
1650 // and we must also restore its size because it isn't expected to
1651 // change just because the window was hidden
1652 win->SetSize(rectOrig);
1656 // refresh it once again after the end to ensure that everything is in
1658 win->SendSizeEvent();
1661 [anim setDelegate:nil];
1662 [animDelegate release];
1668 bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
1669 wxShowEffect effect,
1672 return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
1675 void wxWidgetCocoaImpl::Raise()
1680 void wxWidgetCocoaImpl::Lower()
1685 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
1690 // We should do something like this, but it wasn't working in 10.4.
1691 if (GetNeedsDisplay() )
1695 NSRect r = wxToNSRect( [m_osxView superview], *rect );
1696 NSSize offset = NSMakeSize((float)dx, (float)dy);
1697 [m_osxView scrollRect:r by:offset];
1701 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
1703 wxWindowMac* parent = GetWXPeer()->GetParent();
1704 // under Cocoa we might have a contentView in the wxParent to which we have to
1705 // adjust the coordinates
1706 if (parent && [m_osxView superview] != parent->GetHandle() )
1708 int cx = 0,cy = 0,cw = 0,ch = 0;
1709 if ( parent->GetPeer() )
1711 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
1716 [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
1717 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
1718 [m_osxView setFrame:r];
1719 [[m_osxView superview] setNeedsDisplayInRect:r];
1721 wxNSView* wxview = (wxNSView*)m_osxView;
1722 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
1723 if ([wxview respondsToSelector:@selector(updateTrackingArea)] )
1724 [wxview updateTrackingArea];
1726 if ([m_osxView respondsToSelector:@selector(trackingTag)] )
1728 if ( [wxview trackingTag] )
1729 [wxview removeTrackingRect: [wxview trackingTag]];
1731 [wxview setTrackingTag: [wxview addTrackingRect: [m_osxView bounds] owner: wxview userData: nil assumeInside: NO]];
1736 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
1738 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
1742 // under Cocoa we might have a contentView in the wxParent to which we have to
1743 // adjust the coordinates
1744 wxWindowMac* parent = GetWXPeer()->GetParent();
1745 if (parent && [m_osxView superview] != parent->GetHandle() )
1747 int cx = 0,cy = 0,cw = 0,ch = 0;
1748 if ( parent->GetPeer() )
1750 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
1757 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
1759 NSRect rect = [m_osxView frame];
1760 width = (int)rect.size.width;
1761 height = (int)rect.size.height;
1764 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
1766 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
1768 NSView* cv = [m_osxView contentView];
1770 NSRect bounds = [m_osxView bounds];
1771 NSRect rect = [cv frame];
1773 int y = (int)rect.origin.y;
1774 int x = (int)rect.origin.x;
1775 if ( ![ m_osxView isFlipped ] )
1776 y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
1779 width = (int)rect.size.width;
1780 height = (int)rect.size.height;
1785 GetSize( width, height );
1789 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
1792 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
1794 [m_osxView setNeedsDisplay:YES];
1797 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
1799 return [m_osxView needsDisplay];
1802 bool wxWidgetCocoaImpl::CanFocus() const
1804 return [m_osxView canBecomeKeyView] == YES;
1807 bool wxWidgetCocoaImpl::HasFocus() const
1809 return ( FindFocus() == m_osxView );
1812 bool wxWidgetCocoaImpl::SetFocus()
1817 [[m_osxView window] makeKeyAndOrderFront:nil] ;
1818 [[m_osxView window] makeFirstResponder: m_osxView] ;
1823 void wxWidgetCocoaImpl::RemoveFromParent()
1825 [m_osxView removeFromSuperview];
1828 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
1830 NSView* container = parent->GetWXWidget() ;
1831 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
1832 [container addSubview:m_osxView];
1835 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
1837 NSView* targetView = m_osxView;
1838 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
1839 targetView = [(NSScrollView*) m_osxView documentView];
1841 if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
1843 [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
1844 green:(CGFloat) (col.Green() / 255.0)
1845 blue:(CGFloat) (col.Blue() / 255.0)
1846 alpha:(CGFloat) (col.Alpha() / 255.0)]];
1850 bool wxWidgetCocoaImpl::SetBackgroundStyle( wxBackgroundStyle style )
1852 BOOL opaque = ( style == wxBG_STYLE_PAINT );
1854 if ( [m_osxView respondsToSelector:@selector(setOpaque:) ] )
1856 [m_osxView setOpaque: opaque];
1862 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
1864 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
1866 wxCFStringRef cf( title , encoding );
1867 [m_osxView setTitle:cf.AsNSString()];
1869 else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
1871 wxCFStringRef cf( title , encoding );
1872 [m_osxView setStringValue:cf.AsNSString()];
1877 void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
1879 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
1880 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
1881 *pt = wxFromNSPoint( to->GetWXWidget(), p );
1884 wxInt32 wxWidgetCocoaImpl::GetValue() const
1886 return [(NSControl*)m_osxView intValue];
1889 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
1891 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
1893 [m_osxView setIntValue:v];
1895 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
1897 [m_osxView setFloatValue:(double)v];
1899 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
1901 [m_osxView setDoubleValue:(double)v];
1905 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
1907 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
1909 [m_osxView setMinValue:(double)v];
1913 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
1915 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
1917 [m_osxView setMaxValue:(double)v];
1921 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
1923 if ( [m_osxView respondsToSelector:@selector(minValue)] )
1925 return (int)[m_osxView minValue];
1930 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
1932 if ( [m_osxView respondsToSelector:@selector(maxValue)] )
1934 return (int)[m_osxView maxValue];
1939 wxBitmap wxWidgetCocoaImpl::GetBitmap() const
1943 // TODO: how to create a wxBitmap from NSImage?
1945 if ( [m_osxView respondsToSelector:@selector(image:)] )
1946 bmp = [m_osxView image];
1952 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
1954 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
1956 [m_osxView setImage:bitmap.GetNSImage()];
1957 [m_osxView setNeedsDisplay:YES];
1961 void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
1963 if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
1965 NSCellImagePosition pos;
1985 wxFAIL_MSG( "invalid image position" );
1989 [m_osxView setImagePosition:pos];
1993 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
1995 // implementation in subclass
1998 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
2000 r->x = r->y = r->width = r->height = 0;
2002 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
2004 NSRect former = [m_osxView frame];
2005 [m_osxView sizeToFit];
2006 NSRect best = [m_osxView frame];
2007 [m_osxView setFrame:former];
2008 r->width = (int)best.size.width;
2009 r->height = (int)best.size.height;
2013 bool wxWidgetCocoaImpl::IsEnabled() const
2015 NSView* targetView = m_osxView;
2016 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2017 targetView = [(NSScrollView*) m_osxView documentView];
2019 if ( [targetView respondsToSelector:@selector(isEnabled) ] )
2020 return [targetView isEnabled];
2024 void wxWidgetCocoaImpl::Enable( bool enable )
2026 NSView* targetView = m_osxView;
2027 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2028 targetView = [(NSScrollView*) m_osxView documentView];
2030 if ( [targetView respondsToSelector:@selector(setEnabled:) ] )
2031 [targetView setEnabled:enable];
2034 void wxWidgetCocoaImpl::PulseGauge()
2038 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
2042 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
2044 NSControlSize size = NSRegularControlSize;
2048 case wxWINDOW_VARIANT_NORMAL :
2049 size = NSRegularControlSize;
2052 case wxWINDOW_VARIANT_SMALL :
2053 size = NSSmallControlSize;
2056 case wxWINDOW_VARIANT_MINI :
2057 size = NSMiniControlSize;
2060 case wxWINDOW_VARIANT_LARGE :
2061 size = NSRegularControlSize;
2065 wxFAIL_MSG(wxT("unexpected window variant"));
2068 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
2069 [m_osxView setControlSize:size];
2070 else if ([m_osxView respondsToSelector:@selector(cell)])
2072 id cell = [(id)m_osxView cell];
2073 if ([cell respondsToSelector:@selector(setControlSize:)])
2074 [cell setControlSize:size];
2078 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&col, long, bool)
2080 if ([m_osxView respondsToSelector:@selector(setFont:)])
2081 [m_osxView setFont: font.OSXGetNSFont()];
2082 if ([m_osxView respondsToSelector:@selector(setTextColor:)])
2083 [m_osxView setTextColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2084 green:(CGFloat) (col.Green() / 255.0)
2085 blue:(CGFloat) (col.Blue() / 255.0)
2086 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2089 void wxWidgetCocoaImpl::SetToolTip(wxToolTip* tooltip)
2093 wxCFStringRef cf( tooltip->GetTip() , m_wxPeer->GetFont().GetEncoding() );
2094 [m_osxView setToolTip: cf.AsNSString()];
2097 [m_osxView setToolTip: nil];
2101 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
2103 WXWidget c = control ? control : (WXWidget) m_osxView;
2104 wxWidgetImpl::Associate( c, this ) ;
2105 if ([c respondsToSelector:@selector(setAction:)])
2108 [c setAction: @selector(controlAction:)];
2109 if ([c respondsToSelector:@selector(setDoubleAction:)])
2111 [c setDoubleAction: @selector(controlDoubleAction:)];
2117 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
2119 wxKeyEvent wxevent(wxEVT_CHAR);
2120 SetupKeyEvent( wxevent, event, text );
2122 return GetWXPeer()->OSXHandleKeyEvent(wxevent);
2125 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
2127 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
2128 SetupKeyEvent( wxevent, event );
2129 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
2131 // this will fire higher level events, like insertText, to help
2132 // us handle EVT_CHAR, etc.
2136 if ( IsUserPane() && [event type] == NSKeyDown)
2138 long keycode = wxOSXTranslateCocoaKey( event, wxEVT_CHAR );
2140 if ( (keycode > 0 && keycode < WXK_SPACE) || keycode == WXK_DELETE || keycode >= WXK_START )
2142 // eventually we could setup a doCommandBySelector catcher and retransform this into the wx key chars
2143 wxKeyEvent wxevent2(wxevent) ;
2144 wxevent2.SetEventType(wxEVT_CHAR);
2145 wxevent2.m_keyCode = keycode;
2146 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2150 if ( !wxevent.CmdDown() )
2152 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2153 [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
2155 [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
2165 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
2167 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
2168 SetupMouseEvent(wxevent , event) ;
2170 return GetWXPeer()->HandleWindowEvent(wxevent);
2173 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
2175 wxWindow* thisWindow = GetWXPeer();
2176 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
2178 thisWindow->MacInvalidateBorders();
2181 if ( receivedFocus )
2183 wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
2184 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
2185 thisWindow->HandleWindowEvent(eventFocus);
2188 if ( thisWindow->GetCaret() )
2189 thisWindow->GetCaret()->OnSetFocus();
2192 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
2193 event.SetEventObject(thisWindow);
2195 event.SetWindow(otherWindow->GetWXPeer());
2196 thisWindow->HandleWindowEvent(event) ;
2198 else // !receivedFocuss
2201 if ( thisWindow->GetCaret() )
2202 thisWindow->GetCaret()->OnKillFocus();
2205 wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
2207 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
2208 event.SetEventObject(thisWindow);
2210 event.SetWindow(otherWindow->GetWXPeer());
2211 thisWindow->HandleWindowEvent(event) ;
2215 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
2219 NSPoint location = [NSEvent mouseLocation];
2220 location = [[m_osxView window] convertScreenToBase:location];
2221 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
2223 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
2225 [(NSCursor*)cursor.GetHCURSOR() set];
2228 [[m_osxView window] invalidateCursorRectsForView:m_osxView];
2231 void wxWidgetCocoaImpl::CaptureMouse()
2233 [[m_osxView window] disableCursorRects];
2236 void wxWidgetCocoaImpl::ReleaseMouse()
2238 [[m_osxView window] enableCursorRects];
2241 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
2243 m_isFlipped = flipped;
2250 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
2251 wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
2252 long WXUNUSED(style), long WXUNUSED(extraStyle))
2254 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
2255 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
2257 // temporary hook for dnd
2258 [v registerForDraggedTypes:[NSArray arrayWithObjects:
2259 NSStringPboardType, NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSPDFPboardType, nil]];
2261 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v, false, true );
2265 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
2267 NSWindow* tlw = now->GetWXWindow();
2269 wxWidgetCocoaImpl* c = NULL;
2270 if ( now->IsNativeWindowWrapper() )
2272 NSView* cv = [tlw contentView];
2273 c = new wxWidgetCocoaImpl( now, cv, true );
2274 // increase ref count, because the impl destructor will decrement it again
2276 if ( !now->IsShown() )
2282 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2283 c = new wxWidgetCocoaImpl( now, v, true );
2284 c->InstallEventHandler();
2285 [tlw setContentView:v];