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( [NSApp 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] ;
398 NSPoint locationInWindow = [nsEvent locationInWindow];
400 // adjust coordinates for the window of the target view
401 if ( [nsEvent window] != [m_osxView window] )
403 if ( [nsEvent window] != nil )
404 locationInWindow = [[nsEvent window] convertBaseToScreen:locationInWindow];
406 if ( [m_osxView window] != nil )
407 locationInWindow = [[m_osxView window] convertScreenToBase:locationInWindow];
410 NSPoint locationInView = [m_osxView convertPoint:locationInWindow fromView:nil];
411 wxPoint locationInViewWX = wxFromNSPoint( m_osxView, locationInView );
413 // these parameters are not given for all events
414 UInt32 button = [nsEvent buttonNumber];
415 UInt32 clickCount = 0;
417 wxevent.m_x = locationInViewWX.x;
418 wxevent.m_y = locationInViewWX.y;
419 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
420 wxevent.m_controlDown = modifiers & NSControlKeyMask;
421 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
422 wxevent.m_metaDown = modifiers & NSCommandKeyMask;
423 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
425 UInt32 mouseChord = 0;
429 case NSLeftMouseDown :
430 case NSLeftMouseDragged :
433 case NSRightMouseDown :
434 case NSRightMouseDragged :
437 case NSOtherMouseDown :
438 case NSOtherMouseDragged :
443 // a control click is interpreted as a right click
444 bool thisButtonIsFakeRight = false ;
445 if ( button == 0 && (modifiers & NSControlKeyMask) )
448 thisButtonIsFakeRight = true ;
451 // otherwise we report double clicks by connecting a left click with a ctrl-left click
452 if ( clickCount > 1 && button != g_lastButton )
455 // we must make sure that our synthetic 'right' button corresponds in
456 // mouse down, moved and mouse up, and does not deliver a right down and left up
459 case NSLeftMouseDown :
460 case NSRightMouseDown :
461 case NSOtherMouseDown :
462 g_lastButton = button ;
463 g_lastButtonWasFakeRight = thisButtonIsFakeRight ;
470 g_lastButtonWasFakeRight = false ;
472 else if ( g_lastButton == 1 && g_lastButtonWasFakeRight )
473 button = g_lastButton ;
475 // Adjust the chord mask to remove the primary button and add the
476 // secondary button. It is possible that the secondary button is
477 // already pressed, e.g. on a mouse connected to a laptop, but this
478 // possibility is ignored here:
479 if( thisButtonIsFakeRight && ( mouseChord & 1U ) )
480 mouseChord = ((mouseChord & ~1U) | 2U);
483 wxevent.m_leftDown = true ;
485 wxevent.m_rightDown = true ;
487 wxevent.m_middleDown = true ;
489 // translate into wx types
492 case NSLeftMouseDown :
493 case NSRightMouseDown :
494 case NSOtherMouseDown :
495 clickCount = [nsEvent clickCount];
499 wxevent.SetEventType( clickCount > 1 ? wxEVT_LEFT_DCLICK : wxEVT_LEFT_DOWN ) ;
503 wxevent.SetEventType( clickCount > 1 ? wxEVT_RIGHT_DCLICK : wxEVT_RIGHT_DOWN ) ;
507 wxevent.SetEventType( clickCount > 1 ? wxEVT_MIDDLE_DCLICK : wxEVT_MIDDLE_DOWN ) ;
516 case NSRightMouseUp :
517 case NSOtherMouseUp :
518 clickCount = [nsEvent clickCount];
522 wxevent.SetEventType( wxEVT_LEFT_UP ) ;
526 wxevent.SetEventType( wxEVT_RIGHT_UP ) ;
530 wxevent.SetEventType( wxEVT_MIDDLE_UP ) ;
543 wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ;
545 // see http://developer.apple.com/qa/qa2005/qa1453.html
546 // for more details on why we have to look for the exact type
548 const EventRef cEvent = (EventRef) [nsEvent eventRef];
549 bool isMouseScrollEvent = false;
551 isMouseScrollEvent = ::GetEventKind(cEvent) == kEventMouseScroll;
553 if ( isMouseScrollEvent )
555 deltaX = [nsEvent deviceDeltaX];
556 deltaY = [nsEvent deviceDeltaY];
560 deltaX = ([nsEvent deltaX] * 10);
561 deltaY = ([nsEvent deltaY] * 10);
564 wxevent.m_wheelDelta = 10;
565 wxevent.m_linesPerAction = 1;
567 if ( fabs(deltaX) > fabs(deltaY) )
569 wxevent.m_wheelAxis = 1;
570 wxevent.m_wheelRotation = (int)deltaX;
574 wxevent.m_wheelRotation = (int)deltaY;
580 case NSMouseEntered :
581 wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
584 wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
586 case NSLeftMouseDragged :
587 case NSRightMouseDragged :
588 case NSOtherMouseDragged :
590 wxevent.SetEventType( wxEVT_MOTION ) ;
596 wxevent.m_clickCount = clickCount;
597 wxWindowMac* peer = GetWXPeer();
600 wxevent.SetEventObject(peer);
601 wxevent.SetId(peer->GetId()) ;
605 @implementation wxNSView
609 static BOOL initialized = NO;
613 wxOSXCocoaClassAddWXMethods( self );
617 - (void) setTrackingTag: (NSTrackingRectTag)tag
622 - (NSTrackingRectTag) trackingTag
627 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
628 - (void) updateTrackingArea
632 [self removeTrackingArea: _trackingArea];
633 [_trackingArea release];
636 NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingMouseMoved|NSTrackingActiveAlways;
638 NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: [self bounds] options: options owner: self userInfo: nil];
639 [self addTrackingArea: area];
641 _trackingArea = area;
644 - (NSTrackingArea*) trackingArea
646 return _trackingArea;
655 #if wxUSE_DRAG_AND_DROP
657 // see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
658 // for details on the NSPasteboard -> PasteboardRef conversion
660 NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
662 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
664 return NSDragOperationNone;
666 return impl->draggingEntered(sender, self, _cmd);
669 void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
671 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
675 return impl->draggingExited(sender, self, _cmd);
678 NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
680 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
682 return NSDragOperationNone;
684 return impl->draggingUpdated(sender, self, _cmd);
687 BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
689 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
691 return NSDragOperationNone;
693 return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
698 void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
700 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
704 impl->mouseEvent(event, self, _cmd);
707 BOOL wxOSX_acceptsFirstMouse(NSView* WXUNUSED(self), SEL WXUNUSED(_cmd), NSEvent *WXUNUSED(event))
709 // This is needed to support click through, otherwise the first click on a window
710 // will not do anything unless it is the active window already.
714 void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
716 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
720 impl->keyEvent(event, self, _cmd);
723 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
725 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
729 impl->insertText(text, self, _cmd);
732 BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
734 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
738 return impl->performKeyEquivalent(event, self, _cmd);
741 BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
743 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
747 return impl->acceptsFirstResponder(self, _cmd);
750 BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
752 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
756 return impl->becomeFirstResponder(self, _cmd);
759 BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
761 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
765 return impl->resignFirstResponder(self, _cmd);
768 void wxOSX_resetCursorRects(NSView* self, SEL _cmd)
770 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
774 impl->resetCursorRects(self, _cmd);
777 BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
779 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
783 return impl->isFlipped(self, _cmd) ? YES:NO;
786 void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
788 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
792 return impl->drawRect(&rect, self, _cmd);
795 void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
797 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
801 impl->controlAction(self, _cmd, sender);
804 void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
806 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
810 impl->controlDoubleAction(self, _cmd, sender);
813 unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
815 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
816 NSPasteboard *pboard = [sender draggingPasteboard];
817 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
819 wxWindow* wxpeer = GetWXPeer();
820 if ( wxpeer == NULL )
821 return NSDragOperationNone;
823 wxDropTarget* target = wxpeer->GetDropTarget();
824 if ( target == NULL )
825 return NSDragOperationNone;
827 wxDragResult result = wxDragNone;
828 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
829 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
831 if ( sourceDragMask & NSDragOperationLink )
833 else if ( sourceDragMask & NSDragOperationCopy )
835 else if ( sourceDragMask & NSDragOperationMove )
838 PasteboardRef pboardRef;
839 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
840 target->SetCurrentDragPasteboard(pboardRef);
841 result = target->OnEnter(pt.x, pt.y, result);
842 CFRelease(pboardRef);
844 NSDragOperation nsresult = NSDragOperationNone;
848 nsresult = NSDragOperationLink;
850 nsresult = NSDragOperationMove;
852 nsresult = NSDragOperationCopy;
859 void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
861 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
862 NSPasteboard *pboard = [sender draggingPasteboard];
864 wxWindow* wxpeer = GetWXPeer();
865 if ( wxpeer == NULL )
868 wxDropTarget* target = wxpeer->GetDropTarget();
869 if ( target == NULL )
872 PasteboardRef pboardRef;
873 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
874 target->SetCurrentDragPasteboard(pboardRef);
876 CFRelease(pboardRef);
879 unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
881 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
882 NSPasteboard *pboard = [sender draggingPasteboard];
883 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
885 wxWindow* wxpeer = GetWXPeer();
886 if ( wxpeer == NULL )
887 return NSDragOperationNone;
889 wxDropTarget* target = wxpeer->GetDropTarget();
890 if ( target == NULL )
891 return NSDragOperationNone;
893 wxDragResult result = wxDragNone;
894 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
895 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
897 if ( sourceDragMask & NSDragOperationLink )
899 else if ( sourceDragMask & NSDragOperationCopy )
901 else if ( sourceDragMask & NSDragOperationMove )
904 PasteboardRef pboardRef;
905 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
906 target->SetCurrentDragPasteboard(pboardRef);
907 result = target->OnDragOver(pt.x, pt.y, result);
908 CFRelease(pboardRef);
910 NSDragOperation nsresult = NSDragOperationNone;
914 nsresult = NSDragOperationLink;
916 nsresult = NSDragOperationMove;
918 nsresult = NSDragOperationCopy;
925 bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
927 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
929 NSPasteboard *pboard = [sender draggingPasteboard];
930 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
932 wxWindow* wxpeer = GetWXPeer();
933 wxDropTarget* target = wxpeer->GetDropTarget();
934 wxDragResult result = wxDragNone;
935 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
936 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
938 if ( sourceDragMask & NSDragOperationLink )
940 else if ( sourceDragMask & NSDragOperationCopy )
942 else if ( sourceDragMask & NSDragOperationMove )
945 PasteboardRef pboardRef;
946 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
947 target->SetCurrentDragPasteboard(pboardRef);
949 if (target->OnDrop(pt.x, pt.y))
950 result = target->OnData(pt.x, pt.y, result);
952 CFRelease(pboardRef);
954 return result != wxDragNone;
957 typedef void (*wxOSX_TextEventHandlerPtr)(NSView* self, SEL _cmd, NSString *event);
958 typedef void (*wxOSX_EventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
959 typedef BOOL (*wxOSX_PerformKeyEventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
960 typedef BOOL (*wxOSX_FocusHandlerPtr)(NSView* self, SEL _cmd);
961 typedef BOOL (*wxOSX_ResetCursorRectsHandlerPtr)(NSView* self, SEL _cmd);
962 typedef void (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
964 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
966 if ( !DoHandleMouseEvent(event) )
968 // for plain NSView mouse events would propagate to parents otherwise
969 if (!m_wxPeer->MacIsUserPane())
971 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
972 superimpl(slf, (SEL)_cmd, event);
977 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
979 if ( [event type] == NSKeyDown )
980 m_lastKeyDownEvent = event;
981 if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
983 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
984 superimpl(slf, (SEL)_cmd, event);
986 m_lastKeyDownEvent = NULL;
989 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
991 if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
993 wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
994 superimpl(slf, (SEL)_cmd, text);
999 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
1001 wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1002 return superimpl(slf, (SEL)_cmd, event);
1005 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
1007 if ( m_wxPeer->MacIsUserPane() )
1008 return m_wxPeer->AcceptsFocus();
1011 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1012 return superimpl(slf, (SEL)_cmd);
1016 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
1018 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1019 // get the current focus before running becomeFirstResponder
1020 NSView* otherView = FindFocus();
1022 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1023 BOOL r = superimpl(slf, (SEL)_cmd);
1026 DoNotifyFocusEvent( true, otherWindow );
1032 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
1034 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1035 BOOL r = superimpl(slf, (SEL)_cmd);
1036 // get the current focus after running resignFirstResponder
1037 // note that this value isn't reliable, it might return the same view that
1039 NSView* otherView = FindFocus();
1040 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1041 // NSTextViews have an editor as true responder, therefore the might get the
1042 // resign notification if their editor takes over, don't trigger any event then
1043 if ( r && !m_hasEditor)
1045 DoNotifyFocusEvent( false, otherWindow );
1050 void wxWidgetCocoaImpl::resetCursorRects(WXWidget slf, void *_cmd)
1052 wxWindow* wxpeer = GetWXPeer();
1055 NSCursor *cursor = (NSCursor*)wxpeer->GetCursor().GetHCURSOR();
1058 wxOSX_ResetCursorRectsHandlerPtr superimpl = (wxOSX_ResetCursorRectsHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1059 superimpl(slf, (SEL)_cmd);
1063 [slf addCursorRect: [slf bounds]
1069 bool wxWidgetCocoaImpl::isFlipped(WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1075 #define OSX_DEBUG_DRAWING 0
1077 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
1079 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1080 CGContextSaveGState( context );
1082 #if OSX_DEBUG_DRAWING
1083 CGContextBeginPath( context );
1084 CGContextMoveToPoint(context, 0, 0);
1085 NSRect bounds = [self bounds];
1086 CGContextAddLineToPoint(context, 10, 0);
1087 CGContextMoveToPoint(context, 0, 0);
1088 CGContextAddLineToPoint(context, 0, 10);
1089 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1090 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1091 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1092 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1093 CGContextClosePath( context );
1094 CGContextStrokePath(context);
1099 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1100 CGContextScaleCTM( context, 1, -1 );
1104 const NSRect *rects;
1107 [slf getRectsBeingDrawn:&rects count:&count];
1108 for ( int i = 0 ; i < count ; ++i )
1110 updateRgn.Union(wxFromNSRect(slf, rects[i]));
1113 wxWindow* wxpeer = GetWXPeer();
1114 if ( wxpeer->MacGetTopLevelWindow()->GetWindowStyle() & wxFRAME_SHAPED )
1116 int xoffset = 0, yoffset = 0;
1117 wxRegion rgn = wxpeer->MacGetTopLevelWindow()->GetShape();
1118 wxpeer->MacRootWindowToWindow( &xoffset, &yoffset );
1119 rgn.Offset( xoffset, yoffset );
1120 updateRgn.Intersect(rgn);
1123 wxpeer->GetUpdateRegion() = updateRgn;
1124 wxpeer->MacSetCGContextRef( context );
1126 bool handled = wxpeer->MacDoRedraw( 0 );
1127 CGContextRestoreGState( context );
1129 CGContextSaveGState( context );
1133 SEL _cmd = @selector(drawRect:);
1134 wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1135 superimpl(slf, _cmd, *(NSRect*)rect);
1136 CGContextRestoreGState( context );
1137 CGContextSaveGState( context );
1139 wxpeer->MacPaintChildrenBorders();
1140 wxpeer->MacSetCGContextRef( NULL );
1141 CGContextRestoreGState( context );
1144 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1146 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1148 wxpeer->OSXHandleClicked(0);
1151 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1155 void wxWidgetCocoaImpl::controlTextDidChange()
1157 wxWindow* wxpeer = (wxWindow*)GetWXPeer();
1160 wxCommandEvent event(wxEVT_COMMAND_TEXT_UPDATED, wxpeer->GetId());
1161 event.SetEventObject( wxpeer );
1162 event.SetString( static_cast<wxTextCtrl*>(wxpeer)->GetValue() );
1163 wxpeer->HandleWindowEvent( event );
1169 #if OBJC_API_VERSION >= 2
1171 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1172 class_addMethod(c, s, i, t );
1176 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1181 void wxOSXCocoaClassAddWXMethods(Class c)
1184 #if OBJC_API_VERSION < 2
1185 static objc_method wxmethods[] =
1189 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1190 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1191 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1193 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1194 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1195 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1197 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1199 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1200 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1201 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1203 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
1205 wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1206 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1207 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1209 wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1210 wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1211 wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1213 wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1215 wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
1217 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1218 wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1219 wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1220 wxOSX_CLASS_ADD_METHOD(c, @selector(resetCursorRects), (IMP) wxOSX_resetCursorRects, "v@:" )
1222 wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1223 wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1225 wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1226 wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1228 #if wxUSE_DRAG_AND_DROP
1229 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1230 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1231 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1232 wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1235 #if OBJC_API_VERSION < 2
1237 static int method_count = WXSIZEOF( wxmethods );
1238 static objc_method_list *wxmethodlist = NULL;
1239 if ( wxmethodlist == NULL )
1241 wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1242 memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1243 wxmethodlist->method_count = method_count;
1244 wxmethodlist->obsolete = 0;
1246 class_addMethods( c, wxmethodlist );
1251 // C++ implementation class
1254 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1256 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl ) :
1257 wxWidgetImpl( peer, isRootControl )
1262 // check if the user wants to create the control initially hidden
1263 if ( !peer->IsShown() )
1264 SetVisibility(false);
1266 // gc aware handling
1268 CFRetain(m_osxView);
1269 [m_osxView release];
1272 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1277 void wxWidgetCocoaImpl::Init()
1281 m_lastKeyDownEvent = NULL;
1282 m_hasEditor = false;
1285 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1287 RemoveAssociations( this );
1289 if ( !IsRootControl() )
1291 NSView *sv = [m_osxView superview];
1293 [m_osxView removeFromSuperview];
1295 // gc aware handling
1297 CFRelease(m_osxView);
1300 bool wxWidgetCocoaImpl::IsVisible() const
1302 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1305 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1307 [m_osxView setHidden:(visible ? NO:YES)];
1310 // ----------------------------------------------------------------------------
1311 // window animation stuff
1312 // ----------------------------------------------------------------------------
1314 // define a delegate used to refresh the window during animation
1315 @interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
1321 - (id)init:(wxWindow *)win;
1325 // NSAnimationDelegate methods
1326 - (void)animationDidEnd:(NSAnimation*)animation;
1327 - (void)animation:(NSAnimation*)animation
1328 didReachProgressMark:(NSAnimationProgress)progress;
1331 @implementation wxNSAnimationDelegate
1333 - (id)init:(wxWindow *)win
1348 - (void)animation:(NSAnimation*)animation
1349 didReachProgressMark:(NSAnimationProgress)progress
1351 wxUnusedVar(animation);
1352 wxUnusedVar(progress);
1354 m_win->SendSizeEvent();
1357 - (void)animationDidEnd:(NSAnimation*)animation
1359 wxUnusedVar(animation);
1367 wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1369 wxShowEffect effect,
1372 // create the dictionary describing the animation to perform on this view
1374 viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1375 NSMutableDictionary * const
1376 dict = [NSMutableDictionary dictionaryWithCapacity:4];
1377 [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1379 // determine the start and end rectangles assuming we're hiding the window
1380 const wxRect rectOrig = win->GetRect();
1388 if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1389 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1390 effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1391 else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1392 effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1393 effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1394 else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1395 effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1396 effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1397 else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1398 effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1399 effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1404 case wxSHOW_EFFECT_ROLL_TO_LEFT:
1405 case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1409 case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1410 case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1411 rectEnd.x = rectStart.GetRight();
1415 case wxSHOW_EFFECT_ROLL_TO_TOP:
1416 case wxSHOW_EFFECT_SLIDE_TO_TOP:
1420 case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1421 case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1422 rectEnd.y = rectStart.GetBottom();
1426 case wxSHOW_EFFECT_EXPAND:
1427 rectEnd.x = rectStart.x + rectStart.width / 2;
1428 rectEnd.y = rectStart.y + rectStart.height / 2;
1433 case wxSHOW_EFFECT_BLEND:
1434 [dict setObject:(show ? NSViewAnimationFadeInEffect
1435 : NSViewAnimationFadeOutEffect)
1436 forKey:NSViewAnimationEffectKey];
1439 case wxSHOW_EFFECT_NONE:
1440 case wxSHOW_EFFECT_MAX:
1441 wxFAIL_MSG( "unexpected animation effect" );
1445 wxFAIL_MSG( "unknown animation effect" );
1451 // we need to restore it to the original rectangle instead of making it
1453 wxSwap(rectStart, rectEnd);
1455 // and as the window is currently hidden, we need to show it for the
1456 // animation to be visible at all (but don't restore it at its full
1457 // rectangle as it shouldn't appear immediately)
1458 win->SetSize(rectStart);
1462 NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1463 ? [(NSView *)viewOrWin superview]
1465 const NSRect rStart = wxToNSRect(parentView, rectStart);
1466 const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1468 [dict setObject:[NSValue valueWithRect:rStart]
1469 forKey:NSViewAnimationStartFrameKey];
1470 [dict setObject:[NSValue valueWithRect:rEnd]
1471 forKey:NSViewAnimationEndFrameKey];
1473 // create an animation using the values in the above dictionary
1474 NSViewAnimation * const
1475 anim = [[NSViewAnimation alloc]
1476 initWithViewAnimations:[NSArray arrayWithObject:dict]];
1480 // what is a good default duration? Windows uses 200ms, Web frameworks
1481 // use anything from 250ms to 1s... choose something in the middle
1485 [anim setDuration:timeout/1000.]; // duration is in seconds here
1487 // if the window being animated changes its layout depending on its size
1488 // (which is almost always the case) we need to redo it during animation
1490 // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1491 // controls in wxInfoBar visibly jump around)
1492 const int NUM_LAYOUTS = 20;
1493 for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1494 [anim addProgressMark:f];
1496 wxNSAnimationDelegate * const
1497 animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1498 [anim setDelegate:animDelegate];
1499 [anim startAnimation];
1501 // Cocoa is capable of doing animation asynchronously or even from separate
1502 // thread but wx API doesn't provide any way to be notified about the
1503 // animation end and without this we really must ensure that the window has
1504 // the expected (i.e. the same as if a simple Show() had been used) size
1505 // when we return, so block here until the animation finishes
1507 // notice that because the default animation mode is NSAnimationBlocking,
1508 // no user input events ought to be processed from here
1510 wxEventLoopGuarantor ensureEventLoopExistence;
1511 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1512 while ( ![animDelegate isDone] )
1518 // NSViewAnimation is smart enough to hide the NSView being animated at
1519 // the end but we also must ensure that it's hidden for wx too
1522 // and we must also restore its size because it isn't expected to
1523 // change just because the window was hidden
1524 win->SetSize(rectOrig);
1528 // refresh it once again after the end to ensure that everything is in
1530 win->SendSizeEvent();
1533 [anim setDelegate:nil];
1534 [animDelegate release];
1540 bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
1541 wxShowEffect effect,
1544 return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
1547 void wxWidgetCocoaImpl::Raise()
1552 void wxWidgetCocoaImpl::Lower()
1557 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
1562 // We should do something like this, but it wasn't working in 10.4.
1563 if (GetNeedsDisplay() )
1567 NSRect r = wxToNSRect( [m_osxView superview], *rect );
1568 NSSize offset = NSMakeSize((float)dx, (float)dy);
1569 [m_osxView scrollRect:r by:offset];
1573 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
1575 wxWindowMac* parent = GetWXPeer()->GetParent();
1576 // under Cocoa we might have a contentView in the wxParent to which we have to
1577 // adjust the coordinates
1578 if (parent && [m_osxView superview] != parent->GetHandle() )
1580 int cx = 0,cy = 0,cw = 0,ch = 0;
1581 if ( parent->GetPeer() )
1583 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
1588 [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
1589 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
1590 [m_osxView setFrame:r];
1591 [[m_osxView superview] setNeedsDisplayInRect:r];
1593 wxNSView* wxview = (wxNSView*)m_osxView;
1594 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
1595 if ([wxview respondsToSelector:@selector(updateTrackingArea)] )
1596 [wxview updateTrackingArea];
1598 if ([m_osxView respondsToSelector:@selector(trackingTag)] )
1600 if ( [wxview trackingTag] )
1601 [wxview removeTrackingRect: [wxview trackingTag]];
1603 [wxview setTrackingTag: [wxview addTrackingRect: [m_osxView bounds] owner: wxview userData: nil assumeInside: NO]];
1608 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
1610 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
1615 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
1617 NSRect rect = [m_osxView frame];
1618 width = (int)rect.size.width;
1619 height = (int)rect.size.height;
1622 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
1624 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
1626 NSView* cv = [m_osxView contentView];
1628 NSRect bounds = [m_osxView bounds];
1629 NSRect rect = [cv frame];
1631 int y = (int)rect.origin.y;
1632 int x = (int)rect.origin.x;
1633 if ( ![ m_osxView isFlipped ] )
1634 y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
1637 width = (int)rect.size.width;
1638 height = (int)rect.size.height;
1643 GetSize( width, height );
1647 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
1650 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
1652 [m_osxView setNeedsDisplay:YES];
1655 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
1657 return [m_osxView needsDisplay];
1660 bool wxWidgetCocoaImpl::CanFocus() const
1662 return [m_osxView canBecomeKeyView] == YES;
1665 bool wxWidgetCocoaImpl::HasFocus() const
1667 return ( FindFocus() == m_osxView );
1670 bool wxWidgetCocoaImpl::SetFocus()
1675 [[m_osxView window] makeKeyAndOrderFront:nil] ;
1676 [[m_osxView window] makeFirstResponder: m_osxView] ;
1681 void wxWidgetCocoaImpl::RemoveFromParent()
1683 [m_osxView removeFromSuperview];
1686 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
1688 NSView* container = parent->GetWXWidget() ;
1689 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
1690 [container addSubview:m_osxView];
1693 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
1695 NSView* targetView = m_osxView;
1696 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
1697 targetView = [(NSScrollView*) m_osxView documentView];
1699 if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
1701 [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
1702 green:(CGFloat) (col.Green() / 255.0)
1703 blue:(CGFloat) (col.Blue() / 255.0)
1704 alpha:(CGFloat) (col.Alpha() / 255.0)]];
1708 bool wxWidgetCocoaImpl::SetBackgroundStyle( wxBackgroundStyle style )
1710 BOOL opaque = ( style == wxBG_STYLE_PAINT );
1712 if ( [m_osxView respondsToSelector:@selector(setOpaque:) ] )
1714 [m_osxView setOpaque: opaque];
1720 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
1722 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
1724 wxCFStringRef cf( title , encoding );
1725 [m_osxView setTitle:cf.AsNSString()];
1727 else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
1729 wxCFStringRef cf( title , encoding );
1730 [m_osxView setStringValue:cf.AsNSString()];
1735 void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
1737 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
1738 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
1739 *pt = wxFromNSPoint( to->GetWXWidget(), p );
1742 wxInt32 wxWidgetCocoaImpl::GetValue() const
1744 return [(NSControl*)m_osxView intValue];
1747 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
1749 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
1751 [m_osxView setIntValue:v];
1753 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
1755 [m_osxView setFloatValue:(double)v];
1757 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
1759 [m_osxView setDoubleValue:(double)v];
1763 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
1765 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
1767 [m_osxView setMinValue:(double)v];
1771 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
1773 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
1775 [m_osxView setMaxValue:(double)v];
1779 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
1781 if ( [m_osxView respondsToSelector:@selector(getMinValue:)] )
1783 return (int)[m_osxView minValue];
1788 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
1790 if ( [m_osxView respondsToSelector:@selector(getMaxValue:)] )
1792 return (int)[m_osxView maxValue];
1797 wxBitmap wxWidgetCocoaImpl::GetBitmap() const
1801 // TODO: how to create a wxBitmap from NSImage?
1803 if ( [m_osxView respondsToSelector:@selector(image:)] )
1804 bmp = [m_osxView image];
1810 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
1812 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
1814 [m_osxView setImage:bitmap.GetNSImage()];
1815 [m_osxView setNeedsDisplay:YES];
1819 void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
1821 if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
1823 NSCellImagePosition pos;
1843 wxFAIL_MSG( "invalid image position" );
1847 [m_osxView setImagePosition:pos];
1851 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
1853 // implementation in subclass
1856 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
1858 r->x = r->y = r->width = r->height = 0;
1860 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
1862 NSRect former = [m_osxView frame];
1863 [m_osxView sizeToFit];
1864 NSRect best = [m_osxView frame];
1865 [m_osxView setFrame:former];
1866 r->width = (int)best.size.width;
1867 r->height = (int)best.size.height;
1871 bool wxWidgetCocoaImpl::IsEnabled() const
1873 if ( [m_osxView respondsToSelector:@selector(isEnabled) ] )
1874 return [m_osxView isEnabled];
1878 void wxWidgetCocoaImpl::Enable( bool enable )
1880 if ( [m_osxView respondsToSelector:@selector(setEnabled:) ] )
1881 [m_osxView setEnabled:enable];
1884 void wxWidgetCocoaImpl::PulseGauge()
1888 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
1892 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
1894 NSControlSize size = NSRegularControlSize;
1898 case wxWINDOW_VARIANT_NORMAL :
1899 size = NSRegularControlSize;
1902 case wxWINDOW_VARIANT_SMALL :
1903 size = NSSmallControlSize;
1906 case wxWINDOW_VARIANT_MINI :
1907 size = NSMiniControlSize;
1910 case wxWINDOW_VARIANT_LARGE :
1911 size = NSRegularControlSize;
1915 wxFAIL_MSG(wxT("unexpected window variant"));
1918 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
1919 [m_osxView setControlSize:size];
1920 else if ([m_osxView respondsToSelector:@selector(cell)])
1922 id cell = [(id)m_osxView cell];
1923 if ([cell respondsToSelector:@selector(setControlSize:)])
1924 [cell setControlSize:size];
1928 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&col, long, bool)
1930 if ([m_osxView respondsToSelector:@selector(setFont:)])
1931 [m_osxView setFont: font.OSXGetNSFont()];
1932 if ([m_osxView respondsToSelector:@selector(setTextColor:)])
1933 [m_osxView setTextColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
1934 green:(CGFloat) (col.Green() / 255.0)
1935 blue:(CGFloat) (col.Blue() / 255.0)
1936 alpha:(CGFloat) (col.Alpha() / 255.0)]];
1939 void wxWidgetCocoaImpl::SetToolTip(wxToolTip* tooltip)
1943 wxCFStringRef cf( tooltip->GetTip() , m_wxPeer->GetFont().GetEncoding() );
1944 [m_osxView setToolTip: cf.AsNSString()];
1947 [m_osxView setToolTip: nil];
1951 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
1953 WXWidget c = control ? control : (WXWidget) m_osxView;
1954 wxWidgetImpl::Associate( c, this ) ;
1955 if ([c respondsToSelector:@selector(setAction:)])
1958 [c setAction: @selector(controlAction:)];
1959 if ([c respondsToSelector:@selector(setDoubleAction:)])
1961 [c setDoubleAction: @selector(controlDoubleAction:)];
1967 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
1969 wxKeyEvent wxevent(wxEVT_CHAR);
1970 SetupKeyEvent( wxevent, event, text );
1972 return GetWXPeer()->OSXHandleKeyEvent(wxevent);
1975 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
1977 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1978 SetupKeyEvent( wxevent, event );
1979 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
1981 // this will fire higher level events, like insertText, to help
1982 // us handle EVT_CHAR, etc.
1984 if ( m_wxPeer->MacIsUserPane() && [event type] == NSKeyDown)
1988 if ( wxevent.GetKeyCode() < WXK_SPACE || wxevent.GetKeyCode() == WXK_DELETE || wxevent.GetKeyCode() >= WXK_START )
1990 // eventually we could setup a doCommandBySelector catcher and retransform this into the wx key chars
1991 wxKeyEvent wxevent2(wxevent) ;
1992 wxevent2.SetEventType(wxEVT_CHAR);
1993 GetWXPeer()->OSXHandleKeyEvent(wxevent2);
1997 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
1998 [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
2000 [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
2009 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
2011 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
2012 SetupMouseEvent(wxevent , event) ;
2014 return GetWXPeer()->HandleWindowEvent(wxevent);
2017 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
2019 wxWindow* thisWindow = GetWXPeer();
2020 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
2022 thisWindow->MacInvalidateBorders();
2025 if ( receivedFocus )
2027 wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
2028 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
2029 thisWindow->HandleWindowEvent(eventFocus);
2032 if ( thisWindow->GetCaret() )
2033 thisWindow->GetCaret()->OnSetFocus();
2036 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
2037 event.SetEventObject(thisWindow);
2039 event.SetWindow(otherWindow->GetWXPeer());
2040 thisWindow->HandleWindowEvent(event) ;
2042 else // !receivedFocuss
2045 if ( thisWindow->GetCaret() )
2046 thisWindow->GetCaret()->OnKillFocus();
2049 wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
2051 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
2052 event.SetEventObject(thisWindow);
2054 event.SetWindow(otherWindow->GetWXPeer());
2055 thisWindow->HandleWindowEvent(event) ;
2059 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
2061 NSPoint location = [NSEvent mouseLocation];
2062 location = [[m_osxView window] convertScreenToBase:location];
2063 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
2065 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
2067 [(NSCursor*)cursor.GetHCURSOR() set];
2069 [[m_osxView window] invalidateCursorRectsForView:m_osxView];
2072 void wxWidgetCocoaImpl::CaptureMouse()
2074 [[m_osxView window] disableCursorRects];
2077 void wxWidgetCocoaImpl::ReleaseMouse()
2079 [[m_osxView window] enableCursorRects];
2082 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
2084 m_isFlipped = flipped;
2091 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
2092 wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
2093 long WXUNUSED(style), long WXUNUSED(extraStyle))
2095 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
2096 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
2098 // temporary hook for dnd
2099 [v registerForDraggedTypes:[NSArray arrayWithObjects:
2100 NSStringPboardType, NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSPDFPboardType, nil]];
2102 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v );
2106 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
2108 NSWindow* tlw = now->GetWXWindow();
2110 wxWidgetCocoaImpl* c = NULL;
2111 if ( now->IsNativeWindowWrapper() )
2113 NSView* cv = [tlw contentView];
2114 c = new wxWidgetCocoaImpl( now, cv, true );
2115 // increase ref count, because the impl destructor will decrement it again
2117 if ( !now->IsShown() )
2123 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2124 c = new wxWidgetCocoaImpl( now, v, true );
2125 c->InstallEventHandler();
2126 [tlw setContentView:v];