1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/cocoa/window.mm
3 // Purpose: widgets (non tlw) for cocoa
4 // Author: Stefan Csomor
7 // RCS-ID: $Id: window.mm 48805 2007-09-19 14:52:25Z SC $
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"
22 #include "wx/osx/private.h"
25 #include "wx/evtloop.h"
31 #if wxUSE_DRAG_AND_DROP
36 #include "wx/tooltip.h"
39 #include <objc/objc-runtime.h>
41 // Get the window with the focus
43 NSView* GetViewFromResponder( NSResponder* responder )
46 if ( [responder isKindOfClass:[NSTextView class]] )
48 NSView* delegate = (NSView*) [(NSTextView*)responder delegate];
49 if ( [delegate isKindOfClass:[NSTextField class] ] )
52 view = (NSView*) responder;
56 if ( [responder isKindOfClass:[NSView class]] )
57 view = (NSView*) responder;
62 NSView* GetFocusedViewInWindow( NSWindow* keyWindow )
64 NSView* focusedView = nil;
65 if ( keyWindow != nil )
66 focusedView = GetViewFromResponder([keyWindow firstResponder]);
71 WXWidget wxWidgetImpl::FindFocus()
73 return GetFocusedViewInWindow( [[NSApplication sharedApplication] keyWindow] );
76 NSRect wxOSXGetFrameForControl( wxWindowMac* window , const wxPoint& pos , const wxSize &size , bool adjustForOrigin )
80 window->MacGetBoundsForControl( pos , size , x , y, w, h , adjustForOrigin ) ;
81 wxRect bounds(x,y,w,h);
82 NSView* sv = (window->GetParent()->GetHandle() );
84 return wxToNSRect( sv, bounds );
87 @interface wxNSView : NSView
89 NSTrackingRectTag rectTag;
90 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
91 NSTrackingArea* _trackingArea;
95 // the tracking tag is needed to track mouse enter / exit events
96 - (void) setTrackingTag: (NSTrackingRectTag)tag;
97 - (NSTrackingRectTag) trackingTag;
98 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
99 // under 10.5 we can also track mouse moved events on non-focused windows if
100 // we use the new NSTrackingArea APIs.
101 - (void) updateTrackingArea;
102 - (NSTrackingArea*) trackingArea;
106 @interface NSView(PossibleMethods)
107 - (void)setTitle:(NSString *)aString;
108 - (void)setStringValue:(NSString *)aString;
109 - (void)setIntValue:(int)anInt;
110 - (void)setFloatValue:(float)aFloat;
111 - (void)setDoubleValue:(double)aDouble;
115 - (void)setMinValue:(double)aDouble;
116 - (void)setMaxValue:(double)aDouble;
121 - (void)setEnabled:(BOOL)flag;
123 - (void)setImage:(NSImage *)image;
124 - (void)setControlSize:(NSControlSize)size;
126 - (void)setFont:(NSFont *)fontObject;
130 - (void)setTarget:(id)anObject;
131 - (void)setAction:(SEL)aSelector;
132 - (void)setDoubleAction:(SEL)aSelector;
133 - (void)setBackgroundColor:(NSColor*)aColor;
134 - (void)setOpaque:(BOOL)opaque;
135 - (void)setTextColor:(NSColor *)color;
136 - (void)setImagePosition:(NSCellImagePosition)aPosition;
139 long wxOSXTranslateCocoaKey( NSEvent* event )
143 if ([event type] != NSFlagsChanged)
145 NSString* s = [event charactersIgnoringModifiers];
146 // backspace char reports as delete w/modifiers for some reason
149 switch ( [s characterAtIndex:0] )
156 case NSUpArrowFunctionKey :
159 case NSDownArrowFunctionKey :
162 case NSLeftArrowFunctionKey :
165 case NSRightArrowFunctionKey :
168 case NSInsertFunctionKey :
171 case NSDeleteFunctionKey :
174 case NSHomeFunctionKey :
177 // case NSBeginFunctionKey :
178 // retval = WXK_BEGIN;
180 case NSEndFunctionKey :
183 case NSPageUpFunctionKey :
186 case NSPageDownFunctionKey :
187 retval = WXK_PAGEDOWN;
189 case NSHelpFunctionKey :
193 int intchar = [s characterAtIndex: 0];
194 if ( intchar >= NSF1FunctionKey && intchar <= NSF24FunctionKey )
195 retval = WXK_F1 + (intchar - NSF1FunctionKey );
201 // Some keys don't seem to have constants. The code mimics the approach
202 // taken by WebKit. See:
203 // http://trac.webkit.org/browser/trunk/WebCore/platform/mac/KeyEventMac.mm
204 switch( [event keyCode] )
209 retval = WXK_COMMAND;
213 retval = WXK_CAPITAL;
216 case 56: // Left Shift
217 case 60: // Right Shift
222 case 61: // Right Alt
226 case 59: // Left Ctrl
227 case 62: // Right Ctrl
228 retval = WXK_CONTROL;
240 retval = WXK_NUMPAD_DIVIDE;
243 retval = WXK_NUMPAD_MULTIPLY;
246 retval = WXK_NUMPAD_SUBTRACT;
249 retval = WXK_NUMPAD_ADD;
252 retval = WXK_NUMPAD_ENTER;
255 retval = WXK_NUMPAD_DECIMAL;
258 retval = WXK_NUMPAD0;
261 retval = WXK_NUMPAD1;
264 retval = WXK_NUMPAD2;
267 retval = WXK_NUMPAD3;
270 retval = WXK_NUMPAD4;
273 retval = WXK_NUMPAD5;
276 retval = WXK_NUMPAD6;
279 retval = WXK_NUMPAD7;
282 retval = WXK_NUMPAD8;
285 retval = WXK_NUMPAD9;
288 //retval = [event keyCode];
294 void wxWidgetCocoaImpl::SetupKeyEvent(wxKeyEvent &wxevent , NSEvent * nsEvent, NSString* charString)
296 UInt32 modifiers = [nsEvent modifierFlags] ;
297 int eventType = [nsEvent type];
299 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
300 wxevent.m_controlDown = modifiers & NSControlKeyMask;
301 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
302 wxevent.m_metaDown = modifiers & NSCommandKeyMask;
304 wxevent.m_rawCode = [nsEvent keyCode];
305 wxevent.m_rawFlags = modifiers;
307 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
310 if ( eventType != NSFlagsChanged )
312 NSString* nschars = [nsEvent charactersIgnoringModifiers];
315 // if charString is set, it did not come from key up / key down
316 wxevent.SetEventType( wxEVT_CHAR );
317 chars = wxCFStringRef::AsString(charString);
321 chars = wxCFStringRef::AsString(nschars);
325 int aunichar = chars.Length() > 0 ? chars[0] : 0;
328 if (wxevent.GetEventType() != wxEVT_CHAR)
330 keyval = wxOSXTranslateCocoaKey(nsEvent) ;
334 wxevent.SetEventType( wxEVT_KEY_DOWN ) ;
337 wxevent.SetEventType( wxEVT_KEY_UP ) ;
339 case NSFlagsChanged :
343 wxevent.SetEventType( wxevent.m_controlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
346 wxevent.SetEventType( wxevent.m_shiftDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
349 wxevent.SetEventType( wxevent.m_altDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
352 wxevent.SetEventType( wxevent.m_metaDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
363 if ( wxevent.GetEventType() == wxEVT_KEY_UP || wxevent.GetEventType() == wxEVT_KEY_DOWN )
364 keyval = wxToupper( aunichar ) ;
370 wxevent.m_uniChar = aunichar;
372 wxevent.m_keyCode = keyval;
374 wxWindowMac* peer = GetWXPeer();
377 wxevent.SetEventObject(peer);
378 wxevent.SetId(peer->GetId()) ;
382 UInt32 g_lastButton = 0 ;
383 bool g_lastButtonWasFakeRight = false ;
385 // better scroll wheel support
386 // see http://lists.apple.com/archives/cocoa-dev/2007/Feb/msg00050.html
388 @interface NSEvent (DeviceDelta)
389 - (float)deviceDeltaX;
390 - (float)deviceDeltaY;
393 void wxWidgetCocoaImpl::SetupMouseEvent( wxMouseEvent &wxevent , NSEvent * nsEvent )
395 int eventType = [nsEvent type];
396 UInt32 modifiers = [nsEvent modifierFlags] ;
397 wxPoint screenMouseLocation = wxFromNSPoint( NULL, [nsEvent locationInWindow]);
399 // these parameters are not given for all events
400 UInt32 button = [nsEvent buttonNumber];
401 UInt32 clickCount = 0;
403 wxevent.m_x = screenMouseLocation.x;
404 wxevent.m_y = screenMouseLocation.y;
405 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
406 wxevent.m_controlDown = modifiers & NSControlKeyMask;
407 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
408 wxevent.m_metaDown = modifiers & NSCommandKeyMask;
409 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
411 UInt32 mouseChord = 0;
415 case NSLeftMouseDown :
416 case NSLeftMouseDragged :
419 case NSRightMouseDown :
420 case NSRightMouseDragged :
423 case NSOtherMouseDown :
424 case NSOtherMouseDragged :
429 // a control click is interpreted as a right click
430 bool thisButtonIsFakeRight = false ;
431 if ( button == 0 && (modifiers & NSControlKeyMask) )
434 thisButtonIsFakeRight = true ;
437 // otherwise we report double clicks by connecting a left click with a ctrl-left click
438 if ( clickCount > 1 && button != g_lastButton )
441 // we must make sure that our synthetic 'right' button corresponds in
442 // mouse down, moved and mouse up, and does not deliver a right down and left up
445 case NSLeftMouseDown :
446 case NSRightMouseDown :
447 case NSOtherMouseDown :
448 g_lastButton = button ;
449 g_lastButtonWasFakeRight = thisButtonIsFakeRight ;
456 g_lastButtonWasFakeRight = false ;
458 else if ( g_lastButton == 1 && g_lastButtonWasFakeRight )
459 button = g_lastButton ;
461 // Adjust the chord mask to remove the primary button and add the
462 // secondary button. It is possible that the secondary button is
463 // already pressed, e.g. on a mouse connected to a laptop, but this
464 // possibility is ignored here:
465 if( thisButtonIsFakeRight && ( mouseChord & 1U ) )
466 mouseChord = ((mouseChord & ~1U) | 2U);
469 wxevent.m_leftDown = true ;
471 wxevent.m_rightDown = true ;
473 wxevent.m_middleDown = true ;
475 // translate into wx types
478 case NSLeftMouseDown :
479 case NSRightMouseDown :
480 case NSOtherMouseDown :
481 clickCount = [nsEvent clickCount];
485 wxevent.SetEventType( clickCount > 1 ? wxEVT_LEFT_DCLICK : wxEVT_LEFT_DOWN ) ;
489 wxevent.SetEventType( clickCount > 1 ? wxEVT_RIGHT_DCLICK : wxEVT_RIGHT_DOWN ) ;
493 wxevent.SetEventType( clickCount > 1 ? wxEVT_MIDDLE_DCLICK : wxEVT_MIDDLE_DOWN ) ;
502 case NSRightMouseUp :
503 case NSOtherMouseUp :
504 clickCount = [nsEvent clickCount];
508 wxevent.SetEventType( wxEVT_LEFT_UP ) ;
512 wxevent.SetEventType( wxEVT_RIGHT_UP ) ;
516 wxevent.SetEventType( wxEVT_MIDDLE_UP ) ;
529 wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ;
531 // see http://developer.apple.com/qa/qa2005/qa1453.html
532 // for more details on why we have to look for the exact type
534 const EventRef cEvent = (EventRef) [nsEvent eventRef];
535 bool isMouseScrollEvent = false;
537 isMouseScrollEvent = ::GetEventKind(cEvent) == kEventMouseScroll;
539 if ( isMouseScrollEvent )
541 deltaX = [nsEvent deviceDeltaX];
542 deltaY = [nsEvent deviceDeltaY];
546 deltaX = ([nsEvent deltaX] * 10);
547 deltaY = ([nsEvent deltaY] * 10);
550 wxevent.m_wheelDelta = 10;
551 wxevent.m_linesPerAction = 1;
553 if ( fabs(deltaX) > fabs(deltaY) )
555 wxevent.m_wheelAxis = 1;
556 wxevent.m_wheelRotation = (int)deltaX;
560 wxevent.m_wheelRotation = (int)deltaY;
566 case NSMouseEntered :
567 wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
570 wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
572 case NSLeftMouseDragged :
573 case NSRightMouseDragged :
574 case NSOtherMouseDragged :
576 wxevent.SetEventType( wxEVT_MOTION ) ;
582 wxevent.m_clickCount = clickCount;
583 wxWindowMac* peer = GetWXPeer();
586 wxevent.SetEventObject(peer);
587 wxevent.SetId(peer->GetId()) ;
591 @implementation wxNSView
595 static BOOL initialized = NO;
599 wxOSXCocoaClassAddWXMethods( self );
603 - (void) setTrackingTag: (NSTrackingRectTag)tag
608 - (NSTrackingRectTag) trackingTag
613 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
614 - (void) updateTrackingArea
618 [self removeTrackingArea: _trackingArea];
619 [_trackingArea release];
622 NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingMouseMoved|NSTrackingActiveAlways;
624 NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: [self bounds] options: options owner: self userInfo: nil];
625 [self addTrackingArea: area];
627 _trackingArea = area;
630 - (NSTrackingArea*) trackingArea
632 return _trackingArea;
641 #if wxUSE_DRAG_AND_DROP
643 // see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
644 // for details on the NSPasteboard -> PasteboardRef conversion
646 NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
648 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
650 return NSDragOperationNone;
652 return impl->draggingEntered(sender, self, _cmd);
655 void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
657 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
661 return impl->draggingExited(sender, self, _cmd);
664 NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
666 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
668 return NSDragOperationNone;
670 return impl->draggingUpdated(sender, self, _cmd);
673 BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
675 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
677 return NSDragOperationNone;
679 return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
684 void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
686 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
690 impl->mouseEvent(event, self, _cmd);
693 BOOL wxOSX_acceptsFirstMouse(NSView* WXUNUSED(self), SEL WXUNUSED(_cmd), NSEvent *WXUNUSED(event))
695 // This is needed to support click through, otherwise the first click on a window
696 // will not do anything unless it is the active window already.
700 void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
702 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
706 impl->keyEvent(event, self, _cmd);
709 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
711 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
715 impl->insertText(text, self, _cmd);
718 BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
720 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
724 return impl->performKeyEquivalent(event, self, _cmd);
727 BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
729 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
733 return impl->acceptsFirstResponder(self, _cmd);
736 BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
738 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
742 return impl->becomeFirstResponder(self, _cmd);
745 BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
747 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
751 return impl->resignFirstResponder(self, _cmd);
754 void wxOSX_resetCursorRects(NSView* self, SEL _cmd)
756 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
760 impl->resetCursorRects(self, _cmd);
763 BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
765 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
769 return impl->isFlipped(self, _cmd) ? YES:NO;
772 void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
774 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
778 return impl->drawRect(&rect, self, _cmd);
781 void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
783 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
787 impl->controlAction(self, _cmd, sender);
790 void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
792 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
796 impl->controlDoubleAction(self, _cmd, sender);
799 unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
801 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
802 NSPasteboard *pboard = [sender draggingPasteboard];
803 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
805 wxWindow* wxpeer = GetWXPeer();
806 if ( wxpeer == NULL )
807 return NSDragOperationNone;
809 wxDropTarget* target = wxpeer->GetDropTarget();
810 if ( target == NULL )
811 return NSDragOperationNone;
813 wxDragResult result = wxDragNone;
814 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
815 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
817 if ( sourceDragMask & NSDragOperationLink )
819 else if ( sourceDragMask & NSDragOperationCopy )
821 else if ( sourceDragMask & NSDragOperationMove )
824 PasteboardRef pboardRef;
825 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
826 target->SetCurrentDragPasteboard(pboardRef);
827 result = target->OnEnter(pt.x, pt.y, result);
828 CFRelease(pboardRef);
830 NSDragOperation nsresult = NSDragOperationNone;
834 nsresult = NSDragOperationLink;
836 nsresult = NSDragOperationMove;
838 nsresult = NSDragOperationCopy;
845 void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
847 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
848 NSPasteboard *pboard = [sender draggingPasteboard];
850 wxWindow* wxpeer = GetWXPeer();
851 if ( wxpeer == NULL )
854 wxDropTarget* target = wxpeer->GetDropTarget();
855 if ( target == NULL )
858 PasteboardRef pboardRef;
859 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
860 target->SetCurrentDragPasteboard(pboardRef);
862 CFRelease(pboardRef);
865 unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
867 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
868 NSPasteboard *pboard = [sender draggingPasteboard];
869 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
871 wxWindow* wxpeer = GetWXPeer();
872 if ( wxpeer == NULL )
873 return NSDragOperationNone;
875 wxDropTarget* target = wxpeer->GetDropTarget();
876 if ( target == NULL )
877 return NSDragOperationNone;
879 wxDragResult result = wxDragNone;
880 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
881 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
883 if ( sourceDragMask & NSDragOperationLink )
885 else if ( sourceDragMask & NSDragOperationCopy )
887 else if ( sourceDragMask & NSDragOperationMove )
890 PasteboardRef pboardRef;
891 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
892 target->SetCurrentDragPasteboard(pboardRef);
893 result = target->OnDragOver(pt.x, pt.y, result);
894 CFRelease(pboardRef);
896 NSDragOperation nsresult = NSDragOperationNone;
900 nsresult = NSDragOperationLink;
902 nsresult = NSDragOperationMove;
904 nsresult = NSDragOperationCopy;
911 bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
913 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
915 NSPasteboard *pboard = [sender draggingPasteboard];
916 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
918 wxWindow* wxpeer = GetWXPeer();
919 wxDropTarget* target = wxpeer->GetDropTarget();
920 wxDragResult result = wxDragNone;
921 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
922 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
924 if ( sourceDragMask & NSDragOperationLink )
926 else if ( sourceDragMask & NSDragOperationCopy )
928 else if ( sourceDragMask & NSDragOperationMove )
931 PasteboardRef pboardRef;
932 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
933 target->SetCurrentDragPasteboard(pboardRef);
935 if (target->OnDrop(pt.x, pt.y))
936 result = target->OnData(pt.x, pt.y, result);
938 CFRelease(pboardRef);
940 return result != wxDragNone;
943 typedef void (*wxOSX_TextEventHandlerPtr)(NSView* self, SEL _cmd, NSString *event);
944 typedef void (*wxOSX_EventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
945 typedef BOOL (*wxOSX_PerformKeyEventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
946 typedef BOOL (*wxOSX_FocusHandlerPtr)(NSView* self, SEL _cmd);
947 typedef BOOL (*wxOSX_ResetCursorRectsHandlerPtr)(NSView* self, SEL _cmd);
948 typedef void (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
950 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
952 if ( !DoHandleMouseEvent(event) )
954 // for plain NSView mouse events would propagate to parents otherwise
955 if (!m_wxPeer->MacIsUserPane())
957 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
958 superimpl(slf, (SEL)_cmd, event);
963 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
965 if ( [event type] == NSKeyDown )
966 m_lastKeyDownEvent = event;
967 if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
969 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
970 superimpl(slf, (SEL)_cmd, event);
972 m_lastKeyDownEvent = NULL;
975 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
977 if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
979 wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
980 superimpl(slf, (SEL)_cmd, text);
985 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
987 wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
988 return superimpl(slf, (SEL)_cmd, event);
991 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
993 if ( m_wxPeer->MacIsUserPane() )
994 return m_wxPeer->AcceptsFocus();
997 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
998 return superimpl(slf, (SEL)_cmd);
1002 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
1004 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1005 // get the current focus before running becomeFirstResponder
1006 NSView* otherView = FindFocus();
1008 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1009 BOOL r = superimpl(slf, (SEL)_cmd);
1012 DoNotifyFocusEvent( true, otherWindow );
1018 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
1020 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1021 BOOL r = superimpl(slf, (SEL)_cmd);
1022 // get the current focus after running resignFirstResponder
1023 // note that this value isn't reliable, it might return the same view that
1025 NSView* otherView = FindFocus();
1026 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1027 // NSTextViews have an editor as true responder, therefore the might get the
1028 // resign notification if their editor takes over, don't trigger any event then
1029 if ( r && !m_hasEditor)
1031 DoNotifyFocusEvent( false, otherWindow );
1036 void wxWidgetCocoaImpl::resetCursorRects(WXWidget slf, void *_cmd)
1038 wxWindow* wxpeer = GetWXPeer();
1041 NSCursor *cursor = (NSCursor*)wxpeer->GetCursor().GetHCURSOR();
1044 wxOSX_ResetCursorRectsHandlerPtr superimpl = (wxOSX_ResetCursorRectsHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1045 superimpl(slf, (SEL)_cmd);
1049 [slf addCursorRect: [slf bounds]
1055 bool wxWidgetCocoaImpl::isFlipped(WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1061 #define OSX_DEBUG_DRAWING 0
1063 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
1065 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1066 CGContextSaveGState( context );
1068 #if OSX_DEBUG_DRAWING
1069 CGContextBeginPath( context );
1070 CGContextMoveToPoint(context, 0, 0);
1071 NSRect bounds = [self bounds];
1072 CGContextAddLineToPoint(context, 10, 0);
1073 CGContextMoveToPoint(context, 0, 0);
1074 CGContextAddLineToPoint(context, 0, 10);
1075 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1076 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1077 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1078 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1079 CGContextClosePath( context );
1080 CGContextStrokePath(context);
1085 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1086 CGContextScaleCTM( context, 1, -1 );
1090 const NSRect *rects;
1093 [slf getRectsBeingDrawn:&rects count:&count];
1094 for ( int i = 0 ; i < count ; ++i )
1096 updateRgn.Union(wxFromNSRect(slf, rects[i]));
1099 wxWindow* wxpeer = GetWXPeer();
1100 if ( wxpeer->MacGetTopLevelWindow()->GetWindowStyle() & wxFRAME_SHAPED )
1102 int xoffset = 0, yoffset = 0;
1103 wxRegion rgn = wxpeer->MacGetTopLevelWindow()->GetShape();
1104 wxpeer->MacRootWindowToWindow( &xoffset, &yoffset );
1105 rgn.Offset( xoffset, yoffset );
1106 updateRgn.Intersect(rgn);
1109 wxpeer->GetUpdateRegion() = updateRgn;
1110 wxpeer->MacSetCGContextRef( context );
1112 bool handled = wxpeer->MacDoRedraw( 0 );
1113 CGContextRestoreGState( context );
1115 CGContextSaveGState( context );
1119 SEL _cmd = @selector(drawRect:);
1120 wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1121 superimpl(slf, _cmd, *(NSRect*)rect);
1122 CGContextRestoreGState( context );
1123 CGContextSaveGState( context );
1125 wxpeer->MacPaintChildrenBorders();
1126 wxpeer->MacSetCGContextRef( NULL );
1127 CGContextRestoreGState( context );
1130 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1132 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1134 wxpeer->OSXHandleClicked(0);
1137 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1141 void wxWidgetCocoaImpl::controlTextDidChange()
1143 wxWindow* wxpeer = (wxWindow*)GetWXPeer();
1146 wxCommandEvent event(wxEVT_COMMAND_TEXT_UPDATED, wxpeer->GetId());
1147 event.SetEventObject( wxpeer );
1148 event.SetString( static_cast<wxTextCtrl*>(wxpeer)->GetValue() );
1149 wxpeer->HandleWindowEvent( event );
1155 #if OBJC_API_VERSION >= 2
1157 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1158 class_addMethod(c, s, i, t );
1162 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1167 void wxOSXCocoaClassAddWXMethods(Class c)
1170 #if OBJC_API_VERSION < 2
1171 static objc_method wxmethods[] =
1175 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1176 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1177 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1179 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1180 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1181 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1183 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1185 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1186 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1187 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1189 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
1191 wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1192 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1193 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1195 wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1196 wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1197 wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1199 wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1201 wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
1203 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1204 wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1205 wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1206 wxOSX_CLASS_ADD_METHOD(c, @selector(resetCursorRects), (IMP) wxOSX_resetCursorRects, "v@:" )
1208 wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1209 wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1211 wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1212 wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1214 #if wxUSE_DRAG_AND_DROP
1215 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1216 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1217 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1218 wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1221 #if OBJC_API_VERSION < 2
1223 static int method_count = WXSIZEOF( wxmethods );
1224 static objc_method_list *wxmethodlist = NULL;
1225 if ( wxmethodlist == NULL )
1227 wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1228 memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1229 wxmethodlist->method_count = method_count;
1230 wxmethodlist->obsolete = 0;
1232 class_addMethods( c, wxmethodlist );
1237 // C++ implementation class
1240 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1242 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl ) :
1243 wxWidgetImpl( peer, isRootControl )
1248 // check if the user wants to create the control initially hidden
1249 if ( !peer->IsShown() )
1250 SetVisibility(false);
1252 // gc aware handling
1254 CFRetain(m_osxView);
1255 [m_osxView release];
1258 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1263 void wxWidgetCocoaImpl::Init()
1267 m_lastKeyDownEvent = NULL;
1268 m_hasEditor = false;
1271 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1273 RemoveAssociations( this );
1275 if ( !IsRootControl() )
1277 NSView *sv = [m_osxView superview];
1279 [m_osxView removeFromSuperview];
1281 // gc aware handling
1283 CFRelease(m_osxView);
1286 bool wxWidgetCocoaImpl::IsVisible() const
1288 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1291 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1293 [m_osxView setHidden:(visible ? NO:YES)];
1296 // ----------------------------------------------------------------------------
1297 // window animation stuff
1298 // ----------------------------------------------------------------------------
1300 // define a delegate used to refresh the window during animation
1301 @interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
1307 - (id)init:(wxWindow *)win;
1311 // NSAnimationDelegate methods
1312 - (void)animationDidEnd:(NSAnimation*)animation;
1313 - (void)animation:(NSAnimation*)animation
1314 didReachProgressMark:(NSAnimationProgress)progress;
1317 @implementation wxNSAnimationDelegate
1319 - (id)init:(wxWindow *)win
1334 - (void)animation:(NSAnimation*)animation
1335 didReachProgressMark:(NSAnimationProgress)progress
1337 wxUnusedVar(animation);
1338 wxUnusedVar(progress);
1340 m_win->SendSizeEvent();
1343 - (void)animationDidEnd:(NSAnimation*)animation
1345 wxUnusedVar(animation);
1353 wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1355 wxShowEffect effect,
1358 // create the dictionary describing the animation to perform on this view
1360 viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1361 NSMutableDictionary * const
1362 dict = [NSMutableDictionary dictionaryWithCapacity:4];
1363 [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1365 // determine the start and end rectangles assuming we're hiding the window
1366 const wxRect rectOrig = win->GetRect();
1374 if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1375 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1376 effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1377 else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1378 effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1379 effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1380 else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1381 effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1382 effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1383 else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1384 effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1385 effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1390 case wxSHOW_EFFECT_ROLL_TO_LEFT:
1391 case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1395 case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1396 case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1397 rectEnd.x = rectStart.GetRight();
1401 case wxSHOW_EFFECT_ROLL_TO_TOP:
1402 case wxSHOW_EFFECT_SLIDE_TO_TOP:
1406 case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1407 case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1408 rectEnd.y = rectStart.GetBottom();
1412 case wxSHOW_EFFECT_EXPAND:
1413 rectEnd.x = rectStart.x + rectStart.width / 2;
1414 rectEnd.y = rectStart.y + rectStart.height / 2;
1419 case wxSHOW_EFFECT_BLEND:
1420 [dict setObject:(show ? NSViewAnimationFadeInEffect
1421 : NSViewAnimationFadeOutEffect)
1422 forKey:NSViewAnimationEffectKey];
1425 case wxSHOW_EFFECT_NONE:
1426 case wxSHOW_EFFECT_MAX:
1427 wxFAIL_MSG( "unexpected animation effect" );
1431 wxFAIL_MSG( "unknown animation effect" );
1437 // we need to restore it to the original rectangle instead of making it
1439 wxSwap(rectStart, rectEnd);
1441 // and as the window is currently hidden, we need to show it for the
1442 // animation to be visible at all (but don't restore it at its full
1443 // rectangle as it shouldn't appear immediately)
1444 win->SetSize(rectStart);
1448 NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1449 ? [(NSView *)viewOrWin superview]
1451 const NSRect rStart = wxToNSRect(parentView, rectStart);
1452 const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1454 [dict setObject:[NSValue valueWithRect:rStart]
1455 forKey:NSViewAnimationStartFrameKey];
1456 [dict setObject:[NSValue valueWithRect:rEnd]
1457 forKey:NSViewAnimationEndFrameKey];
1459 // create an animation using the values in the above dictionary
1460 NSViewAnimation * const
1461 anim = [[NSViewAnimation alloc]
1462 initWithViewAnimations:[NSArray arrayWithObject:dict]];
1466 // what is a good default duration? Windows uses 200ms, Web frameworks
1467 // use anything from 250ms to 1s... choose something in the middle
1471 [anim setDuration:timeout/1000.]; // duration is in seconds here
1473 // if the window being animated changes its layout depending on its size
1474 // (which is almost always the case) we need to redo it during animation
1476 // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1477 // controls in wxInfoBar visibly jump around)
1478 const int NUM_LAYOUTS = 20;
1479 for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1480 [anim addProgressMark:f];
1482 wxNSAnimationDelegate * const
1483 animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1484 [anim setDelegate:animDelegate];
1485 [anim startAnimation];
1487 // Cocoa is capable of doing animation asynchronously or even from separate
1488 // thread but wx API doesn't provide any way to be notified about the
1489 // animation end and without this we really must ensure that the window has
1490 // the expected (i.e. the same as if a simple Show() had been used) size
1491 // when we return, so block here until the animation finishes
1493 // notice that because the default animation mode is NSAnimationBlocking,
1494 // no user input events ought to be processed from here
1496 wxEventLoopGuarantor ensureEventLoopExistence;
1497 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1498 while ( ![animDelegate isDone] )
1504 // NSViewAnimation is smart enough to hide the NSView being animated at
1505 // the end but we also must ensure that it's hidden for wx too
1508 // and we must also restore its size because it isn't expected to
1509 // change just because the window was hidden
1510 win->SetSize(rectOrig);
1514 // refresh it once again after the end to ensure that everything is in
1516 win->SendSizeEvent();
1519 [anim setDelegate:nil];
1520 [animDelegate release];
1526 bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
1527 wxShowEffect effect,
1530 return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
1533 void wxWidgetCocoaImpl::Raise()
1538 void wxWidgetCocoaImpl::Lower()
1543 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
1548 // We should do something like this, but it wasn't working in 10.4.
1549 if (GetNeedsDisplay() )
1553 NSRect r = wxToNSRect( [m_osxView superview], *rect );
1554 NSSize offset = NSMakeSize((float)dx, (float)dy);
1555 [m_osxView scrollRect:r by:offset];
1559 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
1561 wxWindowMac* parent = GetWXPeer()->GetParent();
1562 // under Cocoa we might have a contentView in the wxParent to which we have to
1563 // adjust the coordinates
1564 if (parent && [m_osxView superview] != parent->GetHandle() )
1566 int cx = 0,cy = 0,cw = 0,ch = 0;
1567 if ( parent->GetPeer() )
1569 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
1574 [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
1575 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
1576 [m_osxView setFrame:r];
1577 [[m_osxView superview] setNeedsDisplayInRect:r];
1579 wxNSView* wxview = (wxNSView*)m_osxView;
1580 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
1581 if ([wxview respondsToSelector:@selector(updateTrackingArea)] )
1582 [wxview updateTrackingArea];
1584 if ([m_osxView respondsToSelector:@selector(trackingTag)] )
1586 if ( [wxview trackingTag] )
1587 [wxview removeTrackingRect: [wxview trackingTag]];
1589 [wxview setTrackingTag: [wxview addTrackingRect: [m_osxView bounds] owner: wxview userData: nil assumeInside: NO]];
1594 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
1596 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
1601 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
1603 NSRect rect = [m_osxView frame];
1604 width = (int)rect.size.width;
1605 height = (int)rect.size.height;
1608 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
1610 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
1612 NSView* cv = [m_osxView contentView];
1614 NSRect bounds = [m_osxView bounds];
1615 NSRect rect = [cv frame];
1617 int y = (int)rect.origin.y;
1618 int x = (int)rect.origin.x;
1619 if ( ![ m_osxView isFlipped ] )
1620 y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
1623 width = (int)rect.size.width;
1624 height = (int)rect.size.height;
1629 GetSize( width, height );
1633 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
1636 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
1638 [m_osxView setNeedsDisplay:YES];
1641 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
1643 return [m_osxView needsDisplay];
1646 bool wxWidgetCocoaImpl::CanFocus() const
1648 return [m_osxView canBecomeKeyView] == YES;
1651 bool wxWidgetCocoaImpl::HasFocus() const
1653 return ( FindFocus() == m_osxView );
1656 bool wxWidgetCocoaImpl::SetFocus()
1661 [[m_osxView window] makeKeyAndOrderFront:nil] ;
1662 [[m_osxView window] makeFirstResponder: m_osxView] ;
1667 void wxWidgetCocoaImpl::RemoveFromParent()
1669 [m_osxView removeFromSuperview];
1672 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
1674 NSView* container = parent->GetWXWidget() ;
1675 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
1676 [container addSubview:m_osxView];
1679 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
1681 NSView* targetView = m_osxView;
1682 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
1683 targetView = [(NSScrollView*) m_osxView documentView];
1685 if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
1687 [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
1688 green:(CGFloat) (col.Green() / 255.0)
1689 blue:(CGFloat) (col.Blue() / 255.0)
1690 alpha:(CGFloat) (col.Alpha() / 255.0)]];
1694 bool wxWidgetCocoaImpl::SetBackgroundStyle( wxBackgroundStyle style )
1696 BOOL opaque = ( style == wxBG_STYLE_PAINT );
1698 if ( [m_osxView respondsToSelector:@selector(setOpaque:) ] )
1700 [m_osxView setOpaque: opaque];
1706 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
1708 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
1710 wxCFStringRef cf( title , encoding );
1711 [m_osxView setTitle:cf.AsNSString()];
1713 else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
1715 wxCFStringRef cf( title , encoding );
1716 [m_osxView setStringValue:cf.AsNSString()];
1721 void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
1723 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
1724 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
1725 *pt = wxFromNSPoint( to->GetWXWidget(), p );
1728 wxInt32 wxWidgetCocoaImpl::GetValue() const
1730 return [(NSControl*)m_osxView intValue];
1733 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
1735 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
1737 [m_osxView setIntValue:v];
1739 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
1741 [m_osxView setFloatValue:(double)v];
1743 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
1745 [m_osxView setDoubleValue:(double)v];
1749 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
1751 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
1753 [m_osxView setMinValue:(double)v];
1757 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
1759 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
1761 [m_osxView setMaxValue:(double)v];
1765 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
1767 if ( [m_osxView respondsToSelector:@selector(getMinValue:)] )
1769 return (int)[m_osxView minValue];
1774 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
1776 if ( [m_osxView respondsToSelector:@selector(getMaxValue:)] )
1778 return (int)[m_osxView maxValue];
1783 wxBitmap wxWidgetCocoaImpl::GetBitmap() const
1787 // TODO: how to create a wxBitmap from NSImage?
1789 if ( [m_osxView respondsToSelector:@selector(image:)] )
1790 bmp = [m_osxView image];
1796 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
1798 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
1800 [m_osxView setImage:bitmap.GetNSImage()];
1801 [m_osxView setNeedsDisplay:YES];
1805 void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
1807 if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
1809 NSCellImagePosition pos;
1829 wxFAIL_MSG( "invalid image position" );
1833 [m_osxView setImagePosition:pos];
1837 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
1839 // implementation in subclass
1842 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
1844 r->x = r->y = r->width = r->height = 0;
1846 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
1848 NSRect former = [m_osxView frame];
1849 [m_osxView sizeToFit];
1850 NSRect best = [m_osxView frame];
1851 [m_osxView setFrame:former];
1852 r->width = (int)best.size.width;
1853 r->height = (int)best.size.height;
1857 bool wxWidgetCocoaImpl::IsEnabled() const
1859 if ( [m_osxView respondsToSelector:@selector(isEnabled) ] )
1860 return [m_osxView isEnabled];
1864 void wxWidgetCocoaImpl::Enable( bool enable )
1866 if ( [m_osxView respondsToSelector:@selector(setEnabled:) ] )
1867 [m_osxView setEnabled:enable];
1870 void wxWidgetCocoaImpl::PulseGauge()
1874 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
1878 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
1880 NSControlSize size = NSRegularControlSize;
1884 case wxWINDOW_VARIANT_NORMAL :
1885 size = NSRegularControlSize;
1888 case wxWINDOW_VARIANT_SMALL :
1889 size = NSSmallControlSize;
1892 case wxWINDOW_VARIANT_MINI :
1893 size = NSMiniControlSize;
1896 case wxWINDOW_VARIANT_LARGE :
1897 size = NSRegularControlSize;
1901 wxFAIL_MSG(wxT("unexpected window variant"));
1904 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
1905 [m_osxView setControlSize:size];
1906 else if ([m_osxView respondsToSelector:@selector(cell)])
1908 id cell = [(id)m_osxView cell];
1909 if ([cell respondsToSelector:@selector(setControlSize:)])
1910 [cell setControlSize:size];
1914 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&col, long, bool)
1916 if ([m_osxView respondsToSelector:@selector(setFont:)])
1917 [m_osxView setFont: font.OSXGetNSFont()];
1918 if ([m_osxView respondsToSelector:@selector(setTextColor:)])
1919 [m_osxView setTextColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
1920 green:(CGFloat) (col.Green() / 255.0)
1921 blue:(CGFloat) (col.Blue() / 255.0)
1922 alpha:(CGFloat) (col.Alpha() / 255.0)]];
1925 void wxWidgetCocoaImpl::SetToolTip(wxToolTip* tooltip)
1929 wxCFStringRef cf( tooltip->GetTip() , m_wxPeer->GetFont().GetEncoding() );
1930 [m_osxView setToolTip: cf.AsNSString()];
1933 [m_osxView setToolTip: nil];
1937 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
1939 WXWidget c = control ? control : (WXWidget) m_osxView;
1940 wxWidgetImpl::Associate( c, this ) ;
1941 if ([c respondsToSelector:@selector(setAction:)])
1944 [c setAction: @selector(controlAction:)];
1945 if ([c respondsToSelector:@selector(setDoubleAction:)])
1947 [c setDoubleAction: @selector(controlDoubleAction:)];
1953 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
1955 wxKeyEvent wxevent(wxEVT_CHAR);
1956 SetupKeyEvent( wxevent, event, text );
1958 return GetWXPeer()->OSXHandleKeyEvent(wxevent);
1961 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
1963 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1964 SetupKeyEvent( wxevent, event );
1965 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
1967 // this will fire higher level events, like insertText, to help
1968 // us handle EVT_CHAR, etc.
1970 if ( m_wxPeer->MacIsUserPane() && [event type] == NSKeyDown)
1974 if ( wxevent.GetKeyCode() < WXK_SPACE || wxevent.GetKeyCode() == WXK_DELETE || wxevent.GetKeyCode() >= WXK_START )
1976 // eventually we could setup a doCommandBySelector catcher and retransform this into the wx key chars
1977 wxKeyEvent wxevent2(wxevent) ;
1978 wxevent2.SetEventType(wxEVT_CHAR);
1979 GetWXPeer()->OSXHandleKeyEvent(wxevent2);
1983 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
1984 [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
1986 [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
1995 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
1997 NSPoint clickLocation;
1998 clickLocation = [m_osxView convertPoint:[event locationInWindow] fromView:nil];
1999 wxPoint pt = wxFromNSPoint( m_osxView, clickLocation );
2000 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
2001 SetupMouseEvent(wxevent , event) ;
2005 return GetWXPeer()->HandleWindowEvent(wxevent);
2008 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
2010 wxWindow* thisWindow = GetWXPeer();
2011 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
2013 thisWindow->MacInvalidateBorders();
2016 if ( receivedFocus )
2018 wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
2019 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
2020 thisWindow->HandleWindowEvent(eventFocus);
2023 if ( thisWindow->GetCaret() )
2024 thisWindow->GetCaret()->OnSetFocus();
2027 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
2028 event.SetEventObject(thisWindow);
2030 event.SetWindow(otherWindow->GetWXPeer());
2031 thisWindow->HandleWindowEvent(event) ;
2033 else // !receivedFocuss
2036 if ( thisWindow->GetCaret() )
2037 thisWindow->GetCaret()->OnKillFocus();
2040 wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
2042 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
2043 event.SetEventObject(thisWindow);
2045 event.SetWindow(otherWindow->GetWXPeer());
2046 thisWindow->HandleWindowEvent(event) ;
2050 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
2052 NSPoint location = [NSEvent mouseLocation];
2053 location = [[m_osxView window] convertScreenToBase:location];
2054 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
2056 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
2058 [(NSCursor*)cursor.GetHCURSOR() set];
2060 [[m_osxView window] invalidateCursorRectsForView:m_osxView];
2063 void wxWidgetCocoaImpl::CaptureMouse()
2065 [[m_osxView window] disableCursorRects];
2068 void wxWidgetCocoaImpl::ReleaseMouse()
2070 [[m_osxView window] enableCursorRects];
2073 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
2075 m_isFlipped = flipped;
2082 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
2083 wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
2084 long WXUNUSED(style), long WXUNUSED(extraStyle))
2086 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
2087 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
2089 // temporary hook for dnd
2090 [v registerForDraggedTypes:[NSArray arrayWithObjects:
2091 NSStringPboardType, NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSPDFPboardType, nil]];
2093 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v );
2097 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
2099 NSWindow* tlw = now->GetWXWindow();
2101 wxWidgetCocoaImpl* c = NULL;
2102 if ( now->IsNativeWindowWrapper() )
2104 NSView* cv = [tlw contentView];
2105 c = new wxWidgetCocoaImpl( now, cv, true );
2106 // increase ref count, because the impl destructor will decrement it again
2108 if ( !now->IsShown() )
2114 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2115 c = new wxWidgetCocoaImpl( now, v, true );
2116 c->InstallEventHandler();
2117 [tlw setContentView:v];