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"
16 #include "wx/nonownedwnd.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)setTextColor:(NSColor *)color;
135 - (void)setImagePosition:(NSCellImagePosition)aPosition;
138 long wxOSXTranslateCocoaKey( NSEvent* event )
142 if ([event type] != NSFlagsChanged)
144 NSString* s = [event charactersIgnoringModifiers];
145 // backspace char reports as delete w/modifiers for some reason
148 switch ( [s characterAtIndex:0] )
155 case NSUpArrowFunctionKey :
158 case NSDownArrowFunctionKey :
161 case NSLeftArrowFunctionKey :
164 case NSRightArrowFunctionKey :
167 case NSInsertFunctionKey :
170 case NSDeleteFunctionKey :
173 case NSHomeFunctionKey :
176 // case NSBeginFunctionKey :
177 // retval = WXK_BEGIN;
179 case NSEndFunctionKey :
182 case NSPageUpFunctionKey :
185 case NSPageDownFunctionKey :
186 retval = WXK_PAGEDOWN;
188 case NSHelpFunctionKey :
192 int intchar = [s characterAtIndex: 0];
193 if ( intchar >= NSF1FunctionKey && intchar <= NSF24FunctionKey )
194 retval = WXK_F1 + (intchar - NSF1FunctionKey );
200 // Some keys don't seem to have constants. The code mimics the approach
201 // taken by WebKit. See:
202 // http://trac.webkit.org/browser/trunk/WebCore/platform/mac/KeyEventMac.mm
203 switch( [event keyCode] )
208 retval = WXK_COMMAND;
212 retval = WXK_CAPITAL;
215 case 56: // Left Shift
216 case 60: // Right Shift
221 case 61: // Right Alt
225 case 59: // Left Ctrl
226 case 62: // Right Ctrl
227 retval = WXK_CONTROL;
239 retval = WXK_NUMPAD_DIVIDE;
242 retval = WXK_NUMPAD_MULTIPLY;
245 retval = WXK_NUMPAD_SUBTRACT;
248 retval = WXK_NUMPAD_ADD;
251 retval = WXK_NUMPAD_ENTER;
254 retval = WXK_NUMPAD_DECIMAL;
257 retval = WXK_NUMPAD0;
260 retval = WXK_NUMPAD1;
263 retval = WXK_NUMPAD2;
266 retval = WXK_NUMPAD3;
269 retval = WXK_NUMPAD4;
272 retval = WXK_NUMPAD5;
275 retval = WXK_NUMPAD6;
278 retval = WXK_NUMPAD7;
281 retval = WXK_NUMPAD8;
284 retval = WXK_NUMPAD9;
287 //retval = [event keyCode];
293 void wxWidgetCocoaImpl::SetupKeyEvent(wxKeyEvent &wxevent , NSEvent * nsEvent, NSString* charString)
295 UInt32 modifiers = [nsEvent modifierFlags] ;
296 int eventType = [nsEvent type];
298 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
299 wxevent.m_controlDown = modifiers & NSControlKeyMask;
300 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
301 wxevent.m_metaDown = modifiers & NSCommandKeyMask;
303 wxevent.m_rawCode = [nsEvent keyCode];
304 wxevent.m_rawFlags = modifiers;
306 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
309 if ( eventType != NSFlagsChanged )
311 NSString* nschars = [nsEvent charactersIgnoringModifiers];
314 // if charString is set, it did not come from key up / key down
315 wxevent.SetEventType( wxEVT_CHAR );
316 chars = wxCFStringRef::AsString(charString);
320 chars = wxCFStringRef::AsString(nschars);
324 int aunichar = chars.Length() > 0 ? chars[0] : 0;
327 if (wxevent.GetEventType() != wxEVT_CHAR)
329 keyval = wxOSXTranslateCocoaKey(nsEvent) ;
333 wxevent.SetEventType( wxEVT_KEY_DOWN ) ;
336 wxevent.SetEventType( wxEVT_KEY_UP ) ;
338 case NSFlagsChanged :
342 wxevent.SetEventType( wxevent.m_controlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
345 wxevent.SetEventType( wxevent.m_shiftDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
348 wxevent.SetEventType( wxevent.m_altDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
351 wxevent.SetEventType( wxevent.m_metaDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
362 if ( wxevent.GetEventType() == wxEVT_KEY_UP || wxevent.GetEventType() == wxEVT_KEY_DOWN )
363 keyval = wxToupper( aunichar ) ;
369 wxevent.m_uniChar = aunichar;
371 wxevent.m_keyCode = keyval;
373 wxWindowMac* peer = GetWXPeer();
376 wxevent.SetEventObject(peer);
377 wxevent.SetId(peer->GetId()) ;
381 UInt32 g_lastButton = 0 ;
382 bool g_lastButtonWasFakeRight = false ;
384 // better scroll wheel support
385 // see http://lists.apple.com/archives/cocoa-dev/2007/Feb/msg00050.html
387 @interface NSEvent (DeviceDelta)
388 - (float)deviceDeltaX;
389 - (float)deviceDeltaY;
392 void wxWidgetCocoaImpl::SetupMouseEvent( wxMouseEvent &wxevent , NSEvent * nsEvent )
394 int eventType = [nsEvent type];
395 UInt32 modifiers = [nsEvent modifierFlags] ;
396 wxPoint screenMouseLocation = wxFromNSPoint( NULL, [nsEvent locationInWindow]);
398 // these parameters are not given for all events
399 UInt32 button = [nsEvent buttonNumber];
400 UInt32 clickCount = 0;
402 wxevent.m_x = screenMouseLocation.x;
403 wxevent.m_y = screenMouseLocation.y;
404 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
405 wxevent.m_controlDown = modifiers & NSControlKeyMask;
406 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
407 wxevent.m_metaDown = modifiers & NSCommandKeyMask;
408 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
410 UInt32 mouseChord = 0;
414 case NSLeftMouseDown :
415 case NSLeftMouseDragged :
418 case NSRightMouseDown :
419 case NSRightMouseDragged :
422 case NSOtherMouseDown :
423 case NSOtherMouseDragged :
428 // a control click is interpreted as a right click
429 bool thisButtonIsFakeRight = false ;
430 if ( button == 0 && (modifiers & NSControlKeyMask) )
433 thisButtonIsFakeRight = true ;
436 // otherwise we report double clicks by connecting a left click with a ctrl-left click
437 if ( clickCount > 1 && button != g_lastButton )
440 // we must make sure that our synthetic 'right' button corresponds in
441 // mouse down, moved and mouse up, and does not deliver a right down and left up
444 case NSLeftMouseDown :
445 case NSRightMouseDown :
446 case NSOtherMouseDown :
447 g_lastButton = button ;
448 g_lastButtonWasFakeRight = thisButtonIsFakeRight ;
455 g_lastButtonWasFakeRight = false ;
457 else if ( g_lastButton == 1 && g_lastButtonWasFakeRight )
458 button = g_lastButton ;
460 // Adjust the chord mask to remove the primary button and add the
461 // secondary button. It is possible that the secondary button is
462 // already pressed, e.g. on a mouse connected to a laptop, but this
463 // possibility is ignored here:
464 if( thisButtonIsFakeRight && ( mouseChord & 1U ) )
465 mouseChord = ((mouseChord & ~1U) | 2U);
468 wxevent.m_leftDown = true ;
470 wxevent.m_rightDown = true ;
472 wxevent.m_middleDown = true ;
474 // translate into wx types
477 case NSLeftMouseDown :
478 case NSRightMouseDown :
479 case NSOtherMouseDown :
480 clickCount = [nsEvent clickCount];
484 wxevent.SetEventType( clickCount > 1 ? wxEVT_LEFT_DCLICK : wxEVT_LEFT_DOWN ) ;
488 wxevent.SetEventType( clickCount > 1 ? wxEVT_RIGHT_DCLICK : wxEVT_RIGHT_DOWN ) ;
492 wxevent.SetEventType( clickCount > 1 ? wxEVT_MIDDLE_DCLICK : wxEVT_MIDDLE_DOWN ) ;
501 case NSRightMouseUp :
502 case NSOtherMouseUp :
503 clickCount = [nsEvent clickCount];
507 wxevent.SetEventType( wxEVT_LEFT_UP ) ;
511 wxevent.SetEventType( wxEVT_RIGHT_UP ) ;
515 wxevent.SetEventType( wxEVT_MIDDLE_UP ) ;
528 wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ;
530 // see http://developer.apple.com/qa/qa2005/qa1453.html
531 // for more details on why we have to look for the exact type
533 const EventRef cEvent = (EventRef) [nsEvent eventRef];
534 bool isMouseScrollEvent = false;
536 isMouseScrollEvent = ::GetEventKind(cEvent) == kEventMouseScroll;
538 if ( isMouseScrollEvent )
540 deltaX = [nsEvent deviceDeltaX];
541 deltaY = [nsEvent deviceDeltaY];
545 deltaX = ([nsEvent deltaX] * 10);
546 deltaY = ([nsEvent deltaY] * 10);
549 wxevent.m_wheelDelta = 10;
550 wxevent.m_linesPerAction = 1;
552 if ( fabs(deltaX) > fabs(deltaY) )
554 wxevent.m_wheelAxis = 1;
555 wxevent.m_wheelRotation = (int)deltaX;
559 wxevent.m_wheelRotation = (int)deltaY;
565 case NSMouseEntered :
566 wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
569 wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
571 case NSLeftMouseDragged :
572 case NSRightMouseDragged :
573 case NSOtherMouseDragged :
575 wxevent.SetEventType( wxEVT_MOTION ) ;
581 wxevent.m_clickCount = clickCount;
582 wxWindowMac* peer = GetWXPeer();
585 wxevent.SetEventObject(peer);
586 wxevent.SetId(peer->GetId()) ;
590 @implementation wxNSView
594 static BOOL initialized = NO;
598 wxOSXCocoaClassAddWXMethods( self );
602 - (void) setTrackingTag: (NSTrackingRectTag)tag
607 - (NSTrackingRectTag) trackingTag
612 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
613 - (void) updateTrackingArea
617 [self removeTrackingArea: _trackingArea];
618 [_trackingArea release];
621 NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingMouseMoved|NSTrackingActiveAlways;
623 NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: [self bounds] options: options owner: self userInfo: nil];
624 [self addTrackingArea: area];
626 _trackingArea = area;
629 - (NSTrackingArea*) trackingArea
631 return _trackingArea;
640 #if wxUSE_DRAG_AND_DROP
642 // see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
643 // for details on the NSPasteboard -> PasteboardRef conversion
645 NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
647 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
649 return NSDragOperationNone;
651 return impl->draggingEntered(sender, self, _cmd);
654 void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
656 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
660 return impl->draggingExited(sender, self, _cmd);
663 NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
665 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
667 return NSDragOperationNone;
669 return impl->draggingUpdated(sender, self, _cmd);
672 BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
674 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
676 return NSDragOperationNone;
678 return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
683 void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
685 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
689 impl->mouseEvent(event, self, _cmd);
692 BOOL wxOSX_acceptsFirstMouse(NSView* WXUNUSED(self), SEL WXUNUSED(_cmd), NSEvent *WXUNUSED(event))
694 // This is needed to support click through, otherwise the first click on a window
695 // will not do anything unless it is the active window already.
699 void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
701 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
705 impl->keyEvent(event, self, _cmd);
708 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
710 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
714 impl->insertText(text, self, _cmd);
717 BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
719 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
723 return impl->performKeyEquivalent(event, self, _cmd);
726 BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
728 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
732 return impl->acceptsFirstResponder(self, _cmd);
735 BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
737 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
741 return impl->becomeFirstResponder(self, _cmd);
744 BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
746 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
750 return impl->resignFirstResponder(self, _cmd);
753 void wxOSX_resetCursorRects(NSView* self, SEL _cmd)
755 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
759 impl->resetCursorRects(self, _cmd);
762 BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
764 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
768 return impl->isFlipped(self, _cmd) ? YES:NO;
771 void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
773 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
777 return impl->drawRect(&rect, self, _cmd);
780 void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
782 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
786 impl->controlAction(self, _cmd, sender);
789 void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
791 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
795 impl->controlDoubleAction(self, _cmd, sender);
798 unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
800 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
801 NSPasteboard *pboard = [sender draggingPasteboard];
802 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
804 wxWindow* wxpeer = GetWXPeer();
805 if ( wxpeer == NULL )
806 return NSDragOperationNone;
808 wxDropTarget* target = wxpeer->GetDropTarget();
809 if ( target == NULL )
810 return NSDragOperationNone;
812 wxDragResult result = wxDragNone;
813 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
814 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
816 if ( sourceDragMask & NSDragOperationLink )
818 else if ( sourceDragMask & NSDragOperationCopy )
820 else if ( sourceDragMask & NSDragOperationMove )
823 PasteboardRef pboardRef;
824 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
825 target->SetCurrentDragPasteboard(pboardRef);
826 result = target->OnEnter(pt.x, pt.y, result);
827 CFRelease(pboardRef);
829 NSDragOperation nsresult = NSDragOperationNone;
833 nsresult = NSDragOperationLink;
835 nsresult = NSDragOperationMove;
837 nsresult = NSDragOperationCopy;
844 void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
846 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
847 NSPasteboard *pboard = [sender draggingPasteboard];
849 wxWindow* wxpeer = GetWXPeer();
850 if ( wxpeer == NULL )
853 wxDropTarget* target = wxpeer->GetDropTarget();
854 if ( target == NULL )
857 PasteboardRef pboardRef;
858 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
859 target->SetCurrentDragPasteboard(pboardRef);
861 CFRelease(pboardRef);
864 unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
866 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
867 NSPasteboard *pboard = [sender draggingPasteboard];
868 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
870 wxWindow* wxpeer = GetWXPeer();
871 if ( wxpeer == NULL )
872 return NSDragOperationNone;
874 wxDropTarget* target = wxpeer->GetDropTarget();
875 if ( target == NULL )
876 return NSDragOperationNone;
878 wxDragResult result = wxDragNone;
879 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
880 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
882 if ( sourceDragMask & NSDragOperationLink )
884 else if ( sourceDragMask & NSDragOperationCopy )
886 else if ( sourceDragMask & NSDragOperationMove )
889 PasteboardRef pboardRef;
890 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
891 target->SetCurrentDragPasteboard(pboardRef);
892 result = target->OnDragOver(pt.x, pt.y, result);
893 CFRelease(pboardRef);
895 NSDragOperation nsresult = NSDragOperationNone;
899 nsresult = NSDragOperationLink;
901 nsresult = NSDragOperationMove;
903 nsresult = NSDragOperationCopy;
910 bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
912 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
914 NSPasteboard *pboard = [sender draggingPasteboard];
915 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
917 wxWindow* wxpeer = GetWXPeer();
918 wxDropTarget* target = wxpeer->GetDropTarget();
919 wxDragResult result = wxDragNone;
920 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
921 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
923 if ( sourceDragMask & NSDragOperationLink )
925 else if ( sourceDragMask & NSDragOperationCopy )
927 else if ( sourceDragMask & NSDragOperationMove )
930 PasteboardRef pboardRef;
931 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
932 target->SetCurrentDragPasteboard(pboardRef);
934 if (target->OnDrop(pt.x, pt.y))
935 result = target->OnData(pt.x, pt.y, result);
937 CFRelease(pboardRef);
939 return result != wxDragNone;
942 typedef void (*wxOSX_TextEventHandlerPtr)(NSView* self, SEL _cmd, NSString *event);
943 typedef void (*wxOSX_EventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
944 typedef BOOL (*wxOSX_PerformKeyEventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
945 typedef BOOL (*wxOSX_FocusHandlerPtr)(NSView* self, SEL _cmd);
946 typedef BOOL (*wxOSX_ResetCursorRectsHandlerPtr)(NSView* self, SEL _cmd);
947 typedef void (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
949 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
951 if ( !DoHandleMouseEvent(event) )
953 // for plain NSView mouse events would propagate to parents otherwise
954 if (!m_wxPeer->MacIsUserPane())
956 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
957 superimpl(slf, (SEL)_cmd, event);
962 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
964 if ( [event type] == NSKeyDown )
965 m_lastKeyDownEvent = event;
966 if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
968 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
969 superimpl(slf, (SEL)_cmd, event);
971 m_lastKeyDownEvent = NULL;
974 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
976 if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
978 wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
979 superimpl(slf, (SEL)_cmd, text);
984 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
986 wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
987 return superimpl(slf, (SEL)_cmd, event);
990 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
992 if ( m_wxPeer->MacIsUserPane() )
993 return m_wxPeer->AcceptsFocus();
996 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
997 return superimpl(slf, (SEL)_cmd);
1001 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
1003 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1004 // get the current focus before running becomeFirstResponder
1005 NSView* otherView = FindFocus();
1007 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1008 BOOL r = superimpl(slf, (SEL)_cmd);
1011 DoNotifyFocusEvent( true, otherWindow );
1017 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
1019 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1020 BOOL r = superimpl(slf, (SEL)_cmd);
1021 // get the current focus after running resignFirstResponder
1022 // note that this value isn't reliable, it might return the same view that
1024 NSView* otherView = FindFocus();
1025 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1026 // NSTextViews have an editor as true responder, therefore the might get the
1027 // resign notification if their editor takes over, don't trigger any event then
1028 if ( r && !m_hasEditor)
1030 DoNotifyFocusEvent( false, otherWindow );
1035 void wxWidgetCocoaImpl::resetCursorRects(WXWidget slf, void *_cmd)
1037 wxWindow* wxpeer = GetWXPeer();
1040 NSCursor *cursor = (NSCursor*)wxpeer->GetCursor().GetHCURSOR();
1043 wxOSX_ResetCursorRectsHandlerPtr superimpl = (wxOSX_ResetCursorRectsHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1044 superimpl(slf, (SEL)_cmd);
1048 [slf addCursorRect: [slf bounds]
1054 bool wxWidgetCocoaImpl::isFlipped(WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1060 #define OSX_DEBUG_DRAWING 0
1062 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
1064 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1065 CGContextSaveGState( context );
1067 #if OSX_DEBUG_DRAWING
1068 CGContextBeginPath( context );
1069 CGContextMoveToPoint(context, 0, 0);
1070 NSRect bounds = [self bounds];
1071 CGContextAddLineToPoint(context, 10, 0);
1072 CGContextMoveToPoint(context, 0, 0);
1073 CGContextAddLineToPoint(context, 0, 10);
1074 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1075 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1076 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1077 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1078 CGContextClosePath( context );
1079 CGContextStrokePath(context);
1084 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1085 CGContextScaleCTM( context, 1, -1 );
1089 const NSRect *rects;
1092 [slf getRectsBeingDrawn:&rects count:&count];
1093 for ( int i = 0 ; i < count ; ++i )
1095 updateRgn.Union(wxFromNSRect(slf, rects[i]) );
1098 wxWindow* wxpeer = GetWXPeer();
1099 wxpeer->GetUpdateRegion() = updateRgn;
1100 wxpeer->MacSetCGContextRef( context );
1102 bool handled = wxpeer->MacDoRedraw( 0 );
1104 CGContextRestoreGState( context );
1106 CGContextSaveGState( context );
1110 SEL _cmd = @selector(drawRect:);
1111 wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1112 superimpl(slf, _cmd, *(NSRect*)rect);
1113 CGContextRestoreGState( context );
1114 CGContextSaveGState( context );
1116 wxpeer->MacPaintChildrenBorders();
1117 wxpeer->MacSetCGContextRef( NULL );
1118 CGContextRestoreGState( context );
1121 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1123 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1125 wxpeer->OSXHandleClicked(0);
1128 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1132 void wxWidgetCocoaImpl::controlTextDidChange()
1134 wxWindow* wxpeer = (wxWindow*)GetWXPeer();
1137 wxCommandEvent event(wxEVT_COMMAND_TEXT_UPDATED, wxpeer->GetId());
1138 event.SetEventObject( wxpeer );
1139 event.SetString( static_cast<wxTextCtrl*>(wxpeer)->GetValue() );
1140 wxpeer->HandleWindowEvent( event );
1146 #if OBJC_API_VERSION >= 2
1148 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1149 class_addMethod(c, s, i, t );
1153 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1158 void wxOSXCocoaClassAddWXMethods(Class c)
1161 #if OBJC_API_VERSION < 2
1162 static objc_method wxmethods[] =
1166 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1167 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1168 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1170 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1171 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1172 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1174 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1176 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1177 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1178 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1180 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
1182 wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1183 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1184 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1186 wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1187 wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1188 wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1190 wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1192 wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
1194 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1195 wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1196 wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1197 wxOSX_CLASS_ADD_METHOD(c, @selector(resetCursorRects), (IMP) wxOSX_resetCursorRects, "v@:" )
1199 wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1200 wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1202 wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1203 wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1205 #if wxUSE_DRAG_AND_DROP
1206 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1207 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1208 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1209 wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1212 #if OBJC_API_VERSION < 2
1214 static int method_count = WXSIZEOF( wxmethods );
1215 static objc_method_list *wxmethodlist = NULL;
1216 if ( wxmethodlist == NULL )
1218 wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1219 memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1220 wxmethodlist->method_count = method_count;
1221 wxmethodlist->obsolete = 0;
1223 class_addMethods( c, wxmethodlist );
1228 // C++ implementation class
1231 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1233 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl ) :
1234 wxWidgetImpl( peer, isRootControl )
1239 // check if the user wants to create the control initially hidden
1240 if ( !peer->IsShown() )
1241 SetVisibility(false);
1243 // gc aware handling
1245 CFRetain(m_osxView);
1246 [m_osxView release];
1249 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1254 void wxWidgetCocoaImpl::Init()
1258 m_lastKeyDownEvent = NULL;
1259 m_hasEditor = false;
1262 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1264 RemoveAssociations( this );
1266 if ( !IsRootControl() )
1268 NSView *sv = [m_osxView superview];
1270 [m_osxView removeFromSuperview];
1272 // gc aware handling
1274 CFRelease(m_osxView);
1277 bool wxWidgetCocoaImpl::IsVisible() const
1279 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1282 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1284 [m_osxView setHidden:(visible ? NO:YES)];
1287 // ----------------------------------------------------------------------------
1288 // window animation stuff
1289 // ----------------------------------------------------------------------------
1291 // define a delegate used to refresh the window during animation
1292 @interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
1298 - (id)init:(wxWindow *)win;
1302 // NSAnimationDelegate methods
1303 - (void)animationDidEnd:(NSAnimation*)animation;
1304 - (void)animation:(NSAnimation*)animation
1305 didReachProgressMark:(NSAnimationProgress)progress;
1308 @implementation wxNSAnimationDelegate
1310 - (id)init:(wxWindow *)win
1325 - (void)animation:(NSAnimation*)animation
1326 didReachProgressMark:(NSAnimationProgress)progress
1328 wxUnusedVar(animation);
1329 wxUnusedVar(progress);
1331 m_win->SendSizeEvent();
1334 - (void)animationDidEnd:(NSAnimation*)animation
1336 wxUnusedVar(animation);
1344 wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1346 wxShowEffect effect,
1349 // create the dictionary describing the animation to perform on this view
1351 viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1352 NSMutableDictionary * const
1353 dict = [NSMutableDictionary dictionaryWithCapacity:4];
1354 [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1356 // determine the start and end rectangles assuming we're hiding the window
1357 const wxRect rectOrig = win->GetRect();
1365 if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1366 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1367 effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1368 else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1369 effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1370 effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1371 else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1372 effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1373 effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1374 else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1375 effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1376 effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1381 case wxSHOW_EFFECT_ROLL_TO_LEFT:
1382 case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1386 case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1387 case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1388 rectEnd.x = rectStart.GetRight();
1392 case wxSHOW_EFFECT_ROLL_TO_TOP:
1393 case wxSHOW_EFFECT_SLIDE_TO_TOP:
1397 case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1398 case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1399 rectEnd.y = rectStart.GetBottom();
1403 case wxSHOW_EFFECT_EXPAND:
1404 rectEnd.x = rectStart.x + rectStart.width / 2;
1405 rectEnd.y = rectStart.y + rectStart.height / 2;
1410 case wxSHOW_EFFECT_BLEND:
1411 [dict setObject:(show ? NSViewAnimationFadeInEffect
1412 : NSViewAnimationFadeOutEffect)
1413 forKey:NSViewAnimationEffectKey];
1416 case wxSHOW_EFFECT_NONE:
1417 case wxSHOW_EFFECT_MAX:
1418 wxFAIL_MSG( "unexpected animation effect" );
1422 wxFAIL_MSG( "unknown animation effect" );
1428 // we need to restore it to the original rectangle instead of making it
1430 wxSwap(rectStart, rectEnd);
1432 // and as the window is currently hidden, we need to show it for the
1433 // animation to be visible at all (but don't restore it at its full
1434 // rectangle as it shouldn't appear immediately)
1435 win->SetSize(rectStart);
1439 NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1440 ? [(NSView *)viewOrWin superview]
1442 const NSRect rStart = wxToNSRect(parentView, rectStart);
1443 const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1445 [dict setObject:[NSValue valueWithRect:rStart]
1446 forKey:NSViewAnimationStartFrameKey];
1447 [dict setObject:[NSValue valueWithRect:rEnd]
1448 forKey:NSViewAnimationEndFrameKey];
1450 // create an animation using the values in the above dictionary
1451 NSViewAnimation * const
1452 anim = [[NSViewAnimation alloc]
1453 initWithViewAnimations:[NSArray arrayWithObject:dict]];
1457 // what is a good default duration? Windows uses 200ms, Web frameworks
1458 // use anything from 250ms to 1s... choose something in the middle
1462 [anim setDuration:timeout/1000.]; // duration is in seconds here
1464 // if the window being animated changes its layout depending on its size
1465 // (which is almost always the case) we need to redo it during animation
1467 // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1468 // controls in wxInfoBar visibly jump around)
1469 const int NUM_LAYOUTS = 20;
1470 for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1471 [anim addProgressMark:f];
1473 wxNSAnimationDelegate * const
1474 animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1475 [anim setDelegate:animDelegate];
1476 [anim startAnimation];
1478 // Cocoa is capable of doing animation asynchronously or even from separate
1479 // thread but wx API doesn't provide any way to be notified about the
1480 // animation end and without this we really must ensure that the window has
1481 // the expected (i.e. the same as if a simple Show() had been used) size
1482 // when we return, so block here until the animation finishes
1484 // notice that because the default animation mode is NSAnimationBlocking,
1485 // no user input events ought to be processed from here
1487 wxEventLoopGuarantor ensureEventLoopExistence;
1488 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1489 while ( ![animDelegate isDone] )
1495 // NSViewAnimation is smart enough to hide the NSView being animated at
1496 // the end but we also must ensure that it's hidden for wx too
1499 // and we must also restore its size because it isn't expected to
1500 // change just because the window was hidden
1501 win->SetSize(rectOrig);
1505 // refresh it once again after the end to ensure that everything is in
1507 win->SendSizeEvent();
1510 [anim setDelegate:nil];
1511 [animDelegate release];
1517 bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
1518 wxShowEffect effect,
1521 return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
1524 void wxWidgetCocoaImpl::Raise()
1529 void wxWidgetCocoaImpl::Lower()
1534 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
1539 // We should do something like this, but it wasn't working in 10.4.
1540 if (GetNeedsDisplay() )
1544 NSRect r = wxToNSRect( [m_osxView superview], *rect );
1545 NSSize offset = NSMakeSize((float)dx, (float)dy);
1546 [m_osxView scrollRect:r by:offset];
1550 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
1552 wxWindowMac* parent = GetWXPeer()->GetParent();
1553 // under Cocoa we might have a contentView in the wxParent to which we have to
1554 // adjust the coordinates
1555 if (parent && [m_osxView superview] != parent->GetHandle() )
1557 int cx = 0,cy = 0,cw = 0,ch = 0;
1558 if ( parent->GetPeer() )
1560 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
1565 [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
1566 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
1567 [m_osxView setFrame:r];
1568 [[m_osxView superview] setNeedsDisplayInRect:r];
1570 wxNSView* wxview = (wxNSView*)m_osxView;
1571 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
1572 if ([wxview respondsToSelector:@selector(updateTrackingArea)] )
1573 [wxview updateTrackingArea];
1575 if ([m_osxView respondsToSelector:@selector(trackingTag)] )
1577 if ( [wxview trackingTag] )
1578 [wxview removeTrackingRect: [wxview trackingTag]];
1580 [wxview setTrackingTag: [wxview addTrackingRect: [m_osxView bounds] owner: wxview userData: nil assumeInside: NO]];
1585 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
1587 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
1592 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
1594 NSRect rect = [m_osxView frame];
1595 width = (int)rect.size.width;
1596 height = (int)rect.size.height;
1599 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
1601 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
1603 NSView* cv = [m_osxView contentView];
1605 NSRect bounds = [m_osxView bounds];
1606 NSRect rect = [cv frame];
1608 int y = (int)rect.origin.y;
1609 int x = (int)rect.origin.x;
1610 if ( ![ m_osxView isFlipped ] )
1611 y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
1614 width = (int)rect.size.width;
1615 height = (int)rect.size.height;
1620 GetSize( width, height );
1624 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
1627 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
1629 [m_osxView setNeedsDisplay:YES];
1632 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
1634 return [m_osxView needsDisplay];
1637 bool wxWidgetCocoaImpl::CanFocus() const
1639 return [m_osxView canBecomeKeyView] == YES;
1642 bool wxWidgetCocoaImpl::HasFocus() const
1644 return ( FindFocus() == m_osxView );
1647 bool wxWidgetCocoaImpl::SetFocus()
1652 [[m_osxView window] makeKeyAndOrderFront:nil] ;
1653 [[m_osxView window] makeFirstResponder: m_osxView] ;
1658 void wxWidgetCocoaImpl::RemoveFromParent()
1660 [m_osxView removeFromSuperview];
1663 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
1665 NSView* container = parent->GetWXWidget() ;
1666 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
1667 [container addSubview:m_osxView];
1670 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
1672 NSView* targetView = m_osxView;
1673 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
1674 targetView = [(NSScrollView*) m_osxView documentView];
1676 if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
1678 [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
1679 green:(CGFloat) (col.Green() / 255.0)
1680 blue:(CGFloat) (col.Blue() / 255.0)
1681 alpha:(CGFloat) (col.Alpha() / 255.0)]];
1685 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
1687 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
1689 wxCFStringRef cf( title , encoding );
1690 [m_osxView setTitle:cf.AsNSString()];
1692 else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
1694 wxCFStringRef cf( title , encoding );
1695 [m_osxView setStringValue:cf.AsNSString()];
1700 void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
1702 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
1703 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
1704 *pt = wxFromNSPoint( to->GetWXWidget(), p );
1707 wxInt32 wxWidgetCocoaImpl::GetValue() const
1709 return [(NSControl*)m_osxView intValue];
1712 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
1714 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
1716 [m_osxView setIntValue:v];
1718 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
1720 [m_osxView setFloatValue:(double)v];
1722 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
1724 [m_osxView setDoubleValue:(double)v];
1728 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
1730 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
1732 [m_osxView setMinValue:(double)v];
1736 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
1738 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
1740 [m_osxView setMaxValue:(double)v];
1744 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
1746 if ( [m_osxView respondsToSelector:@selector(getMinValue:)] )
1748 return (int)[m_osxView minValue];
1753 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
1755 if ( [m_osxView respondsToSelector:@selector(getMaxValue:)] )
1757 return (int)[m_osxView maxValue];
1762 wxBitmap wxWidgetCocoaImpl::GetBitmap() const
1766 // TODO: how to create a wxBitmap from NSImage?
1768 if ( [m_osxView respondsToSelector:@selector(image:)] )
1769 bmp = [m_osxView image];
1775 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
1777 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
1779 [m_osxView setImage:bitmap.GetNSImage()];
1780 [m_osxView setNeedsDisplay:YES];
1784 void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
1786 if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
1788 NSCellImagePosition pos;
1808 wxFAIL_MSG( "invalid image position" );
1812 [m_osxView setImagePosition:pos];
1816 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
1818 // implementation in subclass
1821 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
1823 r->x = r->y = r->width = r->height = 0;
1825 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
1827 NSRect former = [m_osxView frame];
1828 [m_osxView sizeToFit];
1829 NSRect best = [m_osxView frame];
1830 [m_osxView setFrame:former];
1831 r->width = (int)best.size.width;
1832 r->height = (int)best.size.height;
1836 bool wxWidgetCocoaImpl::IsEnabled() const
1838 if ( [m_osxView respondsToSelector:@selector(isEnabled) ] )
1839 return [m_osxView isEnabled];
1843 void wxWidgetCocoaImpl::Enable( bool enable )
1845 if ( [m_osxView respondsToSelector:@selector(setEnabled:) ] )
1846 [m_osxView setEnabled:enable];
1849 void wxWidgetCocoaImpl::PulseGauge()
1853 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
1857 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
1859 NSControlSize size = NSRegularControlSize;
1863 case wxWINDOW_VARIANT_NORMAL :
1864 size = NSRegularControlSize;
1867 case wxWINDOW_VARIANT_SMALL :
1868 size = NSSmallControlSize;
1871 case wxWINDOW_VARIANT_MINI :
1872 size = NSMiniControlSize;
1875 case wxWINDOW_VARIANT_LARGE :
1876 size = NSRegularControlSize;
1880 wxFAIL_MSG(wxT("unexpected window variant"));
1883 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
1884 [m_osxView setControlSize:size];
1885 else if ([m_osxView respondsToSelector:@selector(cell)])
1887 id cell = [(id)m_osxView cell];
1888 if ([cell respondsToSelector:@selector(setControlSize:)])
1889 [cell setControlSize:size];
1893 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&col, long, bool)
1895 if ([m_osxView respondsToSelector:@selector(setFont:)])
1896 [m_osxView setFont: font.OSXGetNSFont()];
1897 if ([m_osxView respondsToSelector:@selector(setTextColor:)])
1898 [m_osxView setTextColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
1899 green:(CGFloat) (col.Green() / 255.0)
1900 blue:(CGFloat) (col.Blue() / 255.0)
1901 alpha:(CGFloat) (col.Alpha() / 255.0)]];
1904 void wxWidgetCocoaImpl::SetToolTip(wxToolTip* tooltip)
1908 wxCFStringRef cf( tooltip->GetTip() , m_wxPeer->GetFont().GetEncoding() );
1909 [m_osxView setToolTip: cf.AsNSString()];
1912 [m_osxView setToolTip: nil];
1916 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
1918 WXWidget c = control ? control : (WXWidget) m_osxView;
1919 wxWidgetImpl::Associate( c, this ) ;
1920 if ([c respondsToSelector:@selector(setAction:)])
1923 [c setAction: @selector(controlAction:)];
1924 if ([c respondsToSelector:@selector(setDoubleAction:)])
1926 [c setDoubleAction: @selector(controlDoubleAction:)];
1932 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
1934 wxKeyEvent wxevent(wxEVT_CHAR);
1935 SetupKeyEvent( wxevent, event, text );
1937 return GetWXPeer()->OSXHandleKeyEvent(wxevent);
1940 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
1942 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1943 SetupKeyEvent( wxevent, event );
1944 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
1946 // this will fire higher level events, like insertText, to help
1947 // us handle EVT_CHAR, etc.
1949 if ( m_wxPeer->MacIsUserPane() && [event type] == NSKeyDown)
1953 if ( wxevent.GetKeyCode() < WXK_SPACE || wxevent.GetKeyCode() == WXK_DELETE || wxevent.GetKeyCode() >= WXK_START )
1955 // eventually we could setup a doCommandBySelector catcher and retransform this into the wx key chars
1956 wxKeyEvent wxevent2(wxevent) ;
1957 wxevent2.SetEventType(wxEVT_CHAR);
1958 GetWXPeer()->OSXHandleKeyEvent(wxevent2);
1962 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
1963 [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
1965 [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
1974 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
1976 NSPoint clickLocation;
1977 clickLocation = [m_osxView convertPoint:[event locationInWindow] fromView:nil];
1978 wxPoint pt = wxFromNSPoint( m_osxView, clickLocation );
1979 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
1980 SetupMouseEvent(wxevent , event) ;
1984 return GetWXPeer()->HandleWindowEvent(wxevent);
1987 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
1989 wxWindow* thisWindow = GetWXPeer();
1990 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
1992 thisWindow->MacInvalidateBorders();
1995 if ( receivedFocus )
1997 wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
1998 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
1999 thisWindow->HandleWindowEvent(eventFocus);
2002 if ( thisWindow->GetCaret() )
2003 thisWindow->GetCaret()->OnSetFocus();
2006 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
2007 event.SetEventObject(thisWindow);
2009 event.SetWindow(otherWindow->GetWXPeer());
2010 thisWindow->HandleWindowEvent(event) ;
2012 else // !receivedFocuss
2015 if ( thisWindow->GetCaret() )
2016 thisWindow->GetCaret()->OnKillFocus();
2019 wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
2021 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
2022 event.SetEventObject(thisWindow);
2024 event.SetWindow(otherWindow->GetWXPeer());
2025 thisWindow->HandleWindowEvent(event) ;
2029 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
2031 NSPoint location = [NSEvent mouseLocation];
2032 location = [[m_osxView window] convertScreenToBase:location];
2033 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
2035 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
2037 [(NSCursor*)cursor.GetHCURSOR() set];
2039 [[m_osxView window] invalidateCursorRectsForView:m_osxView];
2042 void wxWidgetCocoaImpl::CaptureMouse()
2044 [[m_osxView window] disableCursorRects];
2047 void wxWidgetCocoaImpl::ReleaseMouse()
2049 [[m_osxView window] enableCursorRects];
2052 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
2054 m_isFlipped = flipped;
2061 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
2062 wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
2063 long WXUNUSED(style), long WXUNUSED(extraStyle))
2065 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
2066 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
2068 // temporary hook for dnd
2069 [v registerForDraggedTypes:[NSArray arrayWithObjects:
2070 NSStringPboardType, NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSPDFPboardType, nil]];
2072 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v );
2076 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
2078 NSWindow* tlw = now->GetWXWindow();
2079 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2080 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( now, v, true );
2081 c->InstallEventHandler();
2082 [tlw setContentView:v];