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"
19 #include "wx/combobox.h"
23 #include "wx/osx/private.h"
26 #include "wx/evtloop.h"
32 #if wxUSE_DRAG_AND_DROP
37 #include "wx/tooltip.h"
40 #include <objc/objc-runtime.h>
42 // Get the window with the focus
44 NSView* GetViewFromResponder( NSResponder* responder )
47 if ( [responder isKindOfClass:[NSTextView class]] )
49 NSView* delegate = (NSView*) [(NSTextView*)responder delegate];
50 if ( [delegate isKindOfClass:[NSTextField class] ] )
53 view = (NSView*) responder;
57 if ( [responder isKindOfClass:[NSView class]] )
58 view = (NSView*) responder;
63 NSView* GetFocusedViewInWindow( NSWindow* keyWindow )
65 NSView* focusedView = nil;
66 if ( keyWindow != nil )
67 focusedView = GetViewFromResponder([keyWindow firstResponder]);
72 WXWidget wxWidgetImpl::FindFocus()
74 return GetFocusedViewInWindow( [NSApp keyWindow] );
77 NSRect wxOSXGetFrameForControl( wxWindowMac* window , const wxPoint& pos , const wxSize &size , bool adjustForOrigin )
81 window->MacGetBoundsForControl( pos , size , x , y, w, h , adjustForOrigin ) ;
82 wxRect bounds(x,y,w,h);
83 NSView* sv = (window->GetParent()->GetHandle() );
85 return wxToNSRect( sv, bounds );
88 @interface wxNSView : NSView
90 NSTrackingRectTag rectTag;
91 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
92 NSTrackingArea* _trackingArea;
96 // the tracking tag is needed to track mouse enter / exit events
97 - (void) setTrackingTag: (NSTrackingRectTag)tag;
98 - (NSTrackingRectTag) trackingTag;
99 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
100 // under 10.5 we can also track mouse moved events on non-focused windows if
101 // we use the new NSTrackingArea APIs.
102 - (void) updateTrackingArea;
103 - (NSTrackingArea*) trackingArea;
107 @interface NSView(PossibleMethods)
108 - (void)setTitle:(NSString *)aString;
109 - (void)setStringValue:(NSString *)aString;
110 - (void)setIntValue:(int)anInt;
111 - (void)setFloatValue:(float)aFloat;
112 - (void)setDoubleValue:(double)aDouble;
116 - (void)setMinValue:(double)aDouble;
117 - (void)setMaxValue:(double)aDouble;
122 - (void)setEnabled:(BOOL)flag;
124 - (void)setImage:(NSImage *)image;
125 - (void)setControlSize:(NSControlSize)size;
127 - (void)setFont:(NSFont *)fontObject;
131 - (void)setTarget:(id)anObject;
132 - (void)setAction:(SEL)aSelector;
133 - (void)setDoubleAction:(SEL)aSelector;
134 - (void)setBackgroundColor:(NSColor*)aColor;
135 - (void)setOpaque:(BOOL)opaque;
136 - (void)setTextColor:(NSColor *)color;
137 - (void)setImagePosition:(NSCellImagePosition)aPosition;
140 long wxOSXTranslateCocoaKey( NSEvent* event )
144 if ([event type] != NSFlagsChanged)
146 NSString* s = [event charactersIgnoringModifiers];
147 // backspace char reports as delete w/modifiers for some reason
150 switch ( [s characterAtIndex:0] )
157 case NSUpArrowFunctionKey :
160 case NSDownArrowFunctionKey :
163 case NSLeftArrowFunctionKey :
166 case NSRightArrowFunctionKey :
169 case NSInsertFunctionKey :
172 case NSDeleteFunctionKey :
175 case NSHomeFunctionKey :
178 // case NSBeginFunctionKey :
179 // retval = WXK_BEGIN;
181 case NSEndFunctionKey :
184 case NSPageUpFunctionKey :
187 case NSPageDownFunctionKey :
188 retval = WXK_PAGEDOWN;
190 case NSHelpFunctionKey :
194 int intchar = [s characterAtIndex: 0];
195 if ( intchar >= NSF1FunctionKey && intchar <= NSF24FunctionKey )
196 retval = WXK_F1 + (intchar - NSF1FunctionKey );
202 // Some keys don't seem to have constants. The code mimics the approach
203 // taken by WebKit. See:
204 // http://trac.webkit.org/browser/trunk/WebCore/platform/mac/KeyEventMac.mm
205 switch( [event keyCode] )
210 retval = WXK_COMMAND;
214 retval = WXK_CAPITAL;
217 case 56: // Left Shift
218 case 60: // Right Shift
223 case 61: // Right Alt
227 case 59: // Left Ctrl
228 case 62: // Right Ctrl
229 retval = WXK_CONTROL;
241 retval = WXK_NUMPAD_DIVIDE;
244 retval = WXK_NUMPAD_MULTIPLY;
247 retval = WXK_NUMPAD_SUBTRACT;
250 retval = WXK_NUMPAD_ADD;
253 retval = WXK_NUMPAD_ENTER;
256 retval = WXK_NUMPAD_DECIMAL;
259 retval = WXK_NUMPAD0;
262 retval = WXK_NUMPAD1;
265 retval = WXK_NUMPAD2;
268 retval = WXK_NUMPAD3;
271 retval = WXK_NUMPAD4;
274 retval = WXK_NUMPAD5;
277 retval = WXK_NUMPAD6;
280 retval = WXK_NUMPAD7;
283 retval = WXK_NUMPAD8;
286 retval = WXK_NUMPAD9;
289 //retval = [event keyCode];
295 void wxWidgetCocoaImpl::SetupKeyEvent(wxKeyEvent &wxevent , NSEvent * nsEvent, NSString* charString)
297 UInt32 modifiers = [nsEvent modifierFlags] ;
298 int eventType = [nsEvent type];
300 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
301 wxevent.m_controlDown = modifiers & NSControlKeyMask;
302 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
303 wxevent.m_metaDown = modifiers & NSCommandKeyMask;
305 wxevent.m_rawCode = [nsEvent keyCode];
306 wxevent.m_rawFlags = modifiers;
308 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
311 if ( eventType != NSFlagsChanged )
313 NSString* nschars = [nsEvent charactersIgnoringModifiers];
316 // if charString is set, it did not come from key up / key down
317 wxevent.SetEventType( wxEVT_CHAR );
318 chars = wxCFStringRef::AsString(charString);
322 chars = wxCFStringRef::AsString(nschars);
326 int aunichar = chars.Length() > 0 ? chars[0] : 0;
329 if (wxevent.GetEventType() != wxEVT_CHAR)
331 keyval = wxOSXTranslateCocoaKey(nsEvent) ;
335 wxevent.SetEventType( wxEVT_KEY_DOWN ) ;
338 wxevent.SetEventType( wxEVT_KEY_UP ) ;
340 case NSFlagsChanged :
344 wxevent.SetEventType( wxevent.m_controlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
347 wxevent.SetEventType( wxevent.m_shiftDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
350 wxevent.SetEventType( wxevent.m_altDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
353 wxevent.SetEventType( wxevent.m_metaDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
364 if ( wxevent.GetEventType() == wxEVT_KEY_UP || wxevent.GetEventType() == wxEVT_KEY_DOWN )
365 keyval = wxToupper( aunichar ) ;
371 wxevent.m_uniChar = aunichar;
373 wxevent.m_keyCode = keyval;
375 wxWindowMac* peer = GetWXPeer();
378 wxevent.SetEventObject(peer);
379 wxevent.SetId(peer->GetId()) ;
383 UInt32 g_lastButton = 0 ;
384 bool g_lastButtonWasFakeRight = false ;
386 // better scroll wheel support
387 // see http://lists.apple.com/archives/cocoa-dev/2007/Feb/msg00050.html
389 @interface NSEvent (DeviceDelta)
390 - (float)deviceDeltaX;
391 - (float)deviceDeltaY;
394 void wxWidgetCocoaImpl::SetupMouseEvent( wxMouseEvent &wxevent , NSEvent * nsEvent )
396 int eventType = [nsEvent type];
397 UInt32 modifiers = [nsEvent modifierFlags] ;
399 NSPoint locationInWindow = [nsEvent locationInWindow];
401 // adjust coordinates for the window of the target view
402 if ( [nsEvent window] != [m_osxView window] )
404 if ( [nsEvent window] != nil )
405 locationInWindow = [[nsEvent window] convertBaseToScreen:locationInWindow];
407 if ( [m_osxView window] != nil )
408 locationInWindow = [[m_osxView window] convertScreenToBase:locationInWindow];
411 NSPoint locationInView = [m_osxView convertPoint:locationInWindow fromView:nil];
412 wxPoint locationInViewWX = wxFromNSPoint( m_osxView, locationInView );
414 // these parameters are not given for all events
415 UInt32 button = [nsEvent buttonNumber];
416 UInt32 clickCount = 0;
418 wxevent.m_x = locationInViewWX.x;
419 wxevent.m_y = locationInViewWX.y;
420 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
421 wxevent.m_controlDown = modifiers & NSControlKeyMask;
422 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
423 wxevent.m_metaDown = modifiers & NSCommandKeyMask;
424 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
426 UInt32 mouseChord = 0;
430 case NSLeftMouseDown :
431 case NSLeftMouseDragged :
434 case NSRightMouseDown :
435 case NSRightMouseDragged :
438 case NSOtherMouseDown :
439 case NSOtherMouseDragged :
444 // a control click is interpreted as a right click
445 bool thisButtonIsFakeRight = false ;
446 if ( button == 0 && (modifiers & NSControlKeyMask) )
449 thisButtonIsFakeRight = true ;
452 // otherwise we report double clicks by connecting a left click with a ctrl-left click
453 if ( clickCount > 1 && button != g_lastButton )
456 // we must make sure that our synthetic 'right' button corresponds in
457 // mouse down, moved and mouse up, and does not deliver a right down and left up
460 case NSLeftMouseDown :
461 case NSRightMouseDown :
462 case NSOtherMouseDown :
463 g_lastButton = button ;
464 g_lastButtonWasFakeRight = thisButtonIsFakeRight ;
471 g_lastButtonWasFakeRight = false ;
473 else if ( g_lastButton == 1 && g_lastButtonWasFakeRight )
474 button = g_lastButton ;
476 // Adjust the chord mask to remove the primary button and add the
477 // secondary button. It is possible that the secondary button is
478 // already pressed, e.g. on a mouse connected to a laptop, but this
479 // possibility is ignored here:
480 if( thisButtonIsFakeRight && ( mouseChord & 1U ) )
481 mouseChord = ((mouseChord & ~1U) | 2U);
484 wxevent.m_leftDown = true ;
486 wxevent.m_rightDown = true ;
488 wxevent.m_middleDown = true ;
490 // translate into wx types
493 case NSLeftMouseDown :
494 case NSRightMouseDown :
495 case NSOtherMouseDown :
496 clickCount = [nsEvent clickCount];
500 wxevent.SetEventType( clickCount > 1 ? wxEVT_LEFT_DCLICK : wxEVT_LEFT_DOWN ) ;
504 wxevent.SetEventType( clickCount > 1 ? wxEVT_RIGHT_DCLICK : wxEVT_RIGHT_DOWN ) ;
508 wxevent.SetEventType( clickCount > 1 ? wxEVT_MIDDLE_DCLICK : wxEVT_MIDDLE_DOWN ) ;
517 case NSRightMouseUp :
518 case NSOtherMouseUp :
519 clickCount = [nsEvent clickCount];
523 wxevent.SetEventType( wxEVT_LEFT_UP ) ;
527 wxevent.SetEventType( wxEVT_RIGHT_UP ) ;
531 wxevent.SetEventType( wxEVT_MIDDLE_UP ) ;
544 wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ;
546 // see http://developer.apple.com/qa/qa2005/qa1453.html
547 // for more details on why we have to look for the exact type
549 const EventRef cEvent = (EventRef) [nsEvent eventRef];
550 bool isMouseScrollEvent = false;
552 isMouseScrollEvent = ::GetEventKind(cEvent) == kEventMouseScroll;
554 if ( isMouseScrollEvent )
556 deltaX = [nsEvent deviceDeltaX];
557 deltaY = [nsEvent deviceDeltaY];
561 deltaX = ([nsEvent deltaX] * 10);
562 deltaY = ([nsEvent deltaY] * 10);
565 wxevent.m_wheelDelta = 10;
566 wxevent.m_linesPerAction = 1;
568 if ( fabs(deltaX) > fabs(deltaY) )
570 wxevent.m_wheelAxis = 1;
571 wxevent.m_wheelRotation = (int)deltaX;
575 wxevent.m_wheelRotation = (int)deltaY;
581 case NSMouseEntered :
582 wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
585 wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
587 case NSLeftMouseDragged :
588 case NSRightMouseDragged :
589 case NSOtherMouseDragged :
591 wxevent.SetEventType( wxEVT_MOTION ) ;
597 wxevent.m_clickCount = clickCount;
598 wxWindowMac* peer = GetWXPeer();
601 wxevent.SetEventObject(peer);
602 wxevent.SetId(peer->GetId()) ;
606 @implementation wxNSView
610 static BOOL initialized = NO;
614 wxOSXCocoaClassAddWXMethods( self );
618 - (void) setTrackingTag: (NSTrackingRectTag)tag
623 - (NSTrackingRectTag) trackingTag
628 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
629 - (void) updateTrackingArea
633 [self removeTrackingArea: _trackingArea];
634 [_trackingArea release];
637 NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingMouseMoved|NSTrackingActiveAlways;
639 NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: [self bounds] options: options owner: self userInfo: nil];
640 [self addTrackingArea: area];
642 _trackingArea = area;
645 - (NSTrackingArea*) trackingArea
647 return _trackingArea;
656 #if wxUSE_DRAG_AND_DROP
658 // see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
659 // for details on the NSPasteboard -> PasteboardRef conversion
661 NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
663 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
665 return NSDragOperationNone;
667 return impl->draggingEntered(sender, self, _cmd);
670 void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
672 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
676 return impl->draggingExited(sender, self, _cmd);
679 NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
681 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
683 return NSDragOperationNone;
685 return impl->draggingUpdated(sender, self, _cmd);
688 BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
690 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
692 return NSDragOperationNone;
694 return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
699 void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
701 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
705 impl->mouseEvent(event, self, _cmd);
708 BOOL wxOSX_acceptsFirstMouse(NSView* WXUNUSED(self), SEL WXUNUSED(_cmd), NSEvent *WXUNUSED(event))
710 // This is needed to support click through, otherwise the first click on a window
711 // will not do anything unless it is the active window already.
715 void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
717 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
721 impl->keyEvent(event, self, _cmd);
724 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
726 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
730 impl->insertText(text, self, _cmd);
733 BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
735 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
739 return impl->performKeyEquivalent(event, self, _cmd);
742 BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
744 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
748 return impl->acceptsFirstResponder(self, _cmd);
751 BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
753 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
757 return impl->becomeFirstResponder(self, _cmd);
760 BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
762 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
766 return impl->resignFirstResponder(self, _cmd);
769 void wxOSX_resetCursorRects(NSView* self, SEL _cmd)
771 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
775 impl->resetCursorRects(self, _cmd);
778 BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
780 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
784 return impl->isFlipped(self, _cmd) ? YES:NO;
787 void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
789 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
793 return impl->drawRect(&rect, self, _cmd);
796 void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
798 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
802 impl->controlAction(self, _cmd, sender);
805 void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
807 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
811 impl->controlDoubleAction(self, _cmd, sender);
814 unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
816 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
817 NSPasteboard *pboard = [sender draggingPasteboard];
818 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
820 wxWindow* wxpeer = GetWXPeer();
821 if ( wxpeer == NULL )
822 return NSDragOperationNone;
824 wxDropTarget* target = wxpeer->GetDropTarget();
825 if ( target == NULL )
826 return NSDragOperationNone;
828 wxDragResult result = wxDragNone;
829 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
830 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
832 if ( sourceDragMask & NSDragOperationLink )
834 else if ( sourceDragMask & NSDragOperationCopy )
836 else if ( sourceDragMask & NSDragOperationMove )
839 PasteboardRef pboardRef;
840 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
841 target->SetCurrentDragPasteboard(pboardRef);
842 result = target->OnEnter(pt.x, pt.y, result);
843 CFRelease(pboardRef);
845 NSDragOperation nsresult = NSDragOperationNone;
849 nsresult = NSDragOperationLink;
851 nsresult = NSDragOperationMove;
853 nsresult = NSDragOperationCopy;
860 void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
862 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
863 NSPasteboard *pboard = [sender draggingPasteboard];
865 wxWindow* wxpeer = GetWXPeer();
866 if ( wxpeer == NULL )
869 wxDropTarget* target = wxpeer->GetDropTarget();
870 if ( target == NULL )
873 PasteboardRef pboardRef;
874 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
875 target->SetCurrentDragPasteboard(pboardRef);
877 CFRelease(pboardRef);
880 unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
882 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
883 NSPasteboard *pboard = [sender draggingPasteboard];
884 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
886 wxWindow* wxpeer = GetWXPeer();
887 if ( wxpeer == NULL )
888 return NSDragOperationNone;
890 wxDropTarget* target = wxpeer->GetDropTarget();
891 if ( target == NULL )
892 return NSDragOperationNone;
894 wxDragResult result = wxDragNone;
895 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
896 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
898 if ( sourceDragMask & NSDragOperationLink )
900 else if ( sourceDragMask & NSDragOperationCopy )
902 else if ( sourceDragMask & NSDragOperationMove )
905 PasteboardRef pboardRef;
906 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
907 target->SetCurrentDragPasteboard(pboardRef);
908 result = target->OnDragOver(pt.x, pt.y, result);
909 CFRelease(pboardRef);
911 NSDragOperation nsresult = NSDragOperationNone;
915 nsresult = NSDragOperationLink;
917 nsresult = NSDragOperationMove;
919 nsresult = NSDragOperationCopy;
926 bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
928 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
930 NSPasteboard *pboard = [sender draggingPasteboard];
931 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
933 wxWindow* wxpeer = GetWXPeer();
934 wxDropTarget* target = wxpeer->GetDropTarget();
935 wxDragResult result = wxDragNone;
936 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
937 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
939 if ( sourceDragMask & NSDragOperationLink )
941 else if ( sourceDragMask & NSDragOperationCopy )
943 else if ( sourceDragMask & NSDragOperationMove )
946 PasteboardRef pboardRef;
947 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
948 target->SetCurrentDragPasteboard(pboardRef);
950 if (target->OnDrop(pt.x, pt.y))
951 result = target->OnData(pt.x, pt.y, result);
953 CFRelease(pboardRef);
955 return result != wxDragNone;
958 typedef void (*wxOSX_TextEventHandlerPtr)(NSView* self, SEL _cmd, NSString *event);
959 typedef void (*wxOSX_EventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
960 typedef BOOL (*wxOSX_PerformKeyEventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
961 typedef BOOL (*wxOSX_FocusHandlerPtr)(NSView* self, SEL _cmd);
962 typedef BOOL (*wxOSX_ResetCursorRectsHandlerPtr)(NSView* self, SEL _cmd);
963 typedef void (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
965 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
967 if ( !DoHandleMouseEvent(event) )
969 // for plain NSView mouse events would propagate to parents otherwise
970 if (!m_wxPeer->MacIsUserPane())
972 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
973 superimpl(slf, (SEL)_cmd, event);
978 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
980 if ( [event type] == NSKeyDown )
981 m_lastKeyDownEvent = event;
982 if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
984 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
985 superimpl(slf, (SEL)_cmd, event);
987 m_lastKeyDownEvent = NULL;
990 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
992 if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
994 wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
995 superimpl(slf, (SEL)_cmd, text);
1000 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
1002 wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1003 return superimpl(slf, (SEL)_cmd, event);
1006 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
1008 if ( m_wxPeer->MacIsUserPane() )
1009 return m_wxPeer->AcceptsFocus();
1012 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1013 return superimpl(slf, (SEL)_cmd);
1017 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
1019 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1020 // get the current focus before running becomeFirstResponder
1021 NSView* otherView = FindFocus();
1023 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1024 BOOL r = superimpl(slf, (SEL)_cmd);
1027 DoNotifyFocusEvent( true, otherWindow );
1033 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
1035 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1036 BOOL r = superimpl(slf, (SEL)_cmd);
1037 // get the current focus after running resignFirstResponder
1038 // note that this value isn't reliable, it might return the same view that
1040 NSView* otherView = FindFocus();
1041 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1042 // NSTextViews have an editor as true responder, therefore the might get the
1043 // resign notification if their editor takes over, don't trigger any event then
1044 if ( r && !m_hasEditor)
1046 DoNotifyFocusEvent( false, otherWindow );
1051 void wxWidgetCocoaImpl::resetCursorRects(WXWidget slf, void *_cmd)
1053 wxWindow* wxpeer = GetWXPeer();
1056 NSCursor *cursor = (NSCursor*)wxpeer->GetCursor().GetHCURSOR();
1059 wxOSX_ResetCursorRectsHandlerPtr superimpl = (wxOSX_ResetCursorRectsHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1060 superimpl(slf, (SEL)_cmd);
1064 [slf addCursorRect: [slf bounds]
1070 bool wxWidgetCocoaImpl::isFlipped(WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1076 #define OSX_DEBUG_DRAWING 0
1078 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
1080 // preparing the update region
1083 const NSRect *rects;
1086 [slf getRectsBeingDrawn:&rects count:&count];
1087 for ( int i = 0 ; i < count ; ++i )
1089 updateRgn.Union(wxFromNSRect(slf, rects[i]));
1092 wxWindow* wxpeer = GetWXPeer();
1094 if ( wxpeer->MacGetLeftBorderSize() != 0 || wxpeer->MacGetTopBorderSize() != 0 )
1096 // as this update region is in native window locals we must adapt it to wx window local
1097 updateRgn.Offset( wxpeer->MacGetLeftBorderSize() , wxpeer->MacGetTopBorderSize() );
1100 if ( wxpeer->MacGetTopLevelWindow()->GetWindowStyle() & wxFRAME_SHAPED )
1102 int xoffset = 0, yoffset = 0;
1103 wxRegion rgn = wxpeer->MacGetTopLevelWindow()->GetShape();
1104 wxpeer->MacRootWindowToWindow( &xoffset, &yoffset );
1105 rgn.Offset( xoffset, yoffset );
1106 updateRgn.Intersect(rgn);
1109 wxpeer->GetUpdateRegion() = updateRgn;
1111 // setting up the drawing context
1113 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1114 CGContextSaveGState( context );
1116 #if OSX_DEBUG_DRAWING
1117 CGContextBeginPath( context );
1118 CGContextMoveToPoint(context, 0, 0);
1119 NSRect bounds = [self bounds];
1120 CGContextAddLineToPoint(context, 10, 0);
1121 CGContextMoveToPoint(context, 0, 0);
1122 CGContextAddLineToPoint(context, 0, 10);
1123 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1124 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1125 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1126 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1127 CGContextClosePath( context );
1128 CGContextStrokePath(context);
1133 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1134 CGContextScaleCTM( context, 1, -1 );
1137 wxpeer->MacSetCGContextRef( context );
1139 bool handled = wxpeer->MacDoRedraw( 0 );
1140 CGContextRestoreGState( context );
1142 CGContextSaveGState( context );
1146 SEL _cmd = @selector(drawRect:);
1147 wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1148 superimpl(slf, _cmd, *(NSRect*)rect);
1149 CGContextRestoreGState( context );
1150 CGContextSaveGState( context );
1152 wxpeer->MacPaintChildrenBorders();
1153 wxpeer->MacSetCGContextRef( NULL );
1154 CGContextRestoreGState( context );
1157 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1159 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1161 wxpeer->OSXHandleClicked(0);
1164 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1168 void wxWidgetCocoaImpl::controlTextDidChange()
1170 wxWindow* wxpeer = (wxWindow*)GetWXPeer();
1173 // since native rtti doesn't have to be enabled and wx' rtti is not aware of the mixin wxTextEntry, workaround is needed
1174 wxTextCtrl *tc = wxDynamicCast( wxpeer , wxTextCtrl );
1175 wxComboBox *cb = wxDynamicCast( wxpeer , wxComboBox );
1177 tc->SendTextUpdatedEventIfAllowed();
1179 cb->SendTextUpdatedEventIfAllowed();
1182 wxFAIL_MSG("Unexpected class for controlTextDidChange event");
1189 #if OBJC_API_VERSION >= 2
1191 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1192 class_addMethod(c, s, i, t );
1196 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1201 void wxOSXCocoaClassAddWXMethods(Class c)
1204 #if OBJC_API_VERSION < 2
1205 static objc_method wxmethods[] =
1209 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1210 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1211 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1213 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1214 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1215 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1217 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1219 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1220 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1221 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1223 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
1225 wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1226 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1227 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1229 wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1230 wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1231 wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1233 wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1235 wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
1237 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1238 wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1239 wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1240 wxOSX_CLASS_ADD_METHOD(c, @selector(resetCursorRects), (IMP) wxOSX_resetCursorRects, "v@:" )
1242 wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1243 wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1245 wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1246 wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1248 #if wxUSE_DRAG_AND_DROP
1249 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1250 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1251 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1252 wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1255 #if OBJC_API_VERSION < 2
1257 static int method_count = WXSIZEOF( wxmethods );
1258 static objc_method_list *wxmethodlist = NULL;
1259 if ( wxmethodlist == NULL )
1261 wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1262 memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1263 wxmethodlist->method_count = method_count;
1264 wxmethodlist->obsolete = 0;
1266 class_addMethods( c, wxmethodlist );
1271 // C++ implementation class
1274 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1276 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl ) :
1277 wxWidgetImpl( peer, isRootControl )
1282 // check if the user wants to create the control initially hidden
1283 if ( !peer->IsShown() )
1284 SetVisibility(false);
1286 // gc aware handling
1288 CFRetain(m_osxView);
1289 [m_osxView release];
1292 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1297 void wxWidgetCocoaImpl::Init()
1301 m_lastKeyDownEvent = NULL;
1302 m_hasEditor = false;
1305 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1307 RemoveAssociations( this );
1309 if ( !IsRootControl() )
1311 NSView *sv = [m_osxView superview];
1313 [m_osxView removeFromSuperview];
1315 // gc aware handling
1317 CFRelease(m_osxView);
1320 bool wxWidgetCocoaImpl::IsVisible() const
1322 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1325 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1327 [m_osxView setHidden:(visible ? NO:YES)];
1330 // ----------------------------------------------------------------------------
1331 // window animation stuff
1332 // ----------------------------------------------------------------------------
1334 // define a delegate used to refresh the window during animation
1335 @interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
1341 - (id)init:(wxWindow *)win;
1345 // NSAnimationDelegate methods
1346 - (void)animationDidEnd:(NSAnimation*)animation;
1347 - (void)animation:(NSAnimation*)animation
1348 didReachProgressMark:(NSAnimationProgress)progress;
1351 @implementation wxNSAnimationDelegate
1353 - (id)init:(wxWindow *)win
1368 - (void)animation:(NSAnimation*)animation
1369 didReachProgressMark:(NSAnimationProgress)progress
1371 wxUnusedVar(animation);
1372 wxUnusedVar(progress);
1374 m_win->SendSizeEvent();
1377 - (void)animationDidEnd:(NSAnimation*)animation
1379 wxUnusedVar(animation);
1387 wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1389 wxShowEffect effect,
1392 // create the dictionary describing the animation to perform on this view
1394 viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1395 NSMutableDictionary * const
1396 dict = [NSMutableDictionary dictionaryWithCapacity:4];
1397 [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1399 // determine the start and end rectangles assuming we're hiding the window
1400 const wxRect rectOrig = win->GetRect();
1408 if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1409 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1410 effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1411 else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1412 effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1413 effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1414 else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1415 effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1416 effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1417 else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1418 effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1419 effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1424 case wxSHOW_EFFECT_ROLL_TO_LEFT:
1425 case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1429 case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1430 case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1431 rectEnd.x = rectStart.GetRight();
1435 case wxSHOW_EFFECT_ROLL_TO_TOP:
1436 case wxSHOW_EFFECT_SLIDE_TO_TOP:
1440 case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1441 case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1442 rectEnd.y = rectStart.GetBottom();
1446 case wxSHOW_EFFECT_EXPAND:
1447 rectEnd.x = rectStart.x + rectStart.width / 2;
1448 rectEnd.y = rectStart.y + rectStart.height / 2;
1453 case wxSHOW_EFFECT_BLEND:
1454 [dict setObject:(show ? NSViewAnimationFadeInEffect
1455 : NSViewAnimationFadeOutEffect)
1456 forKey:NSViewAnimationEffectKey];
1459 case wxSHOW_EFFECT_NONE:
1460 case wxSHOW_EFFECT_MAX:
1461 wxFAIL_MSG( "unexpected animation effect" );
1465 wxFAIL_MSG( "unknown animation effect" );
1471 // we need to restore it to the original rectangle instead of making it
1473 wxSwap(rectStart, rectEnd);
1475 // and as the window is currently hidden, we need to show it for the
1476 // animation to be visible at all (but don't restore it at its full
1477 // rectangle as it shouldn't appear immediately)
1478 win->SetSize(rectStart);
1482 NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1483 ? [(NSView *)viewOrWin superview]
1485 const NSRect rStart = wxToNSRect(parentView, rectStart);
1486 const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1488 [dict setObject:[NSValue valueWithRect:rStart]
1489 forKey:NSViewAnimationStartFrameKey];
1490 [dict setObject:[NSValue valueWithRect:rEnd]
1491 forKey:NSViewAnimationEndFrameKey];
1493 // create an animation using the values in the above dictionary
1494 NSViewAnimation * const
1495 anim = [[NSViewAnimation alloc]
1496 initWithViewAnimations:[NSArray arrayWithObject:dict]];
1500 // what is a good default duration? Windows uses 200ms, Web frameworks
1501 // use anything from 250ms to 1s... choose something in the middle
1505 [anim setDuration:timeout/1000.]; // duration is in seconds here
1507 // if the window being animated changes its layout depending on its size
1508 // (which is almost always the case) we need to redo it during animation
1510 // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1511 // controls in wxInfoBar visibly jump around)
1512 const int NUM_LAYOUTS = 20;
1513 for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1514 [anim addProgressMark:f];
1516 wxNSAnimationDelegate * const
1517 animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1518 [anim setDelegate:animDelegate];
1519 [anim startAnimation];
1521 // Cocoa is capable of doing animation asynchronously or even from separate
1522 // thread but wx API doesn't provide any way to be notified about the
1523 // animation end and without this we really must ensure that the window has
1524 // the expected (i.e. the same as if a simple Show() had been used) size
1525 // when we return, so block here until the animation finishes
1527 // notice that because the default animation mode is NSAnimationBlocking,
1528 // no user input events ought to be processed from here
1530 wxEventLoopGuarantor ensureEventLoopExistence;
1531 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1532 while ( ![animDelegate isDone] )
1538 // NSViewAnimation is smart enough to hide the NSView being animated at
1539 // the end but we also must ensure that it's hidden for wx too
1542 // and we must also restore its size because it isn't expected to
1543 // change just because the window was hidden
1544 win->SetSize(rectOrig);
1548 // refresh it once again after the end to ensure that everything is in
1550 win->SendSizeEvent();
1553 [anim setDelegate:nil];
1554 [animDelegate release];
1560 bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
1561 wxShowEffect effect,
1564 return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
1567 void wxWidgetCocoaImpl::Raise()
1572 void wxWidgetCocoaImpl::Lower()
1577 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
1582 // We should do something like this, but it wasn't working in 10.4.
1583 if (GetNeedsDisplay() )
1587 NSRect r = wxToNSRect( [m_osxView superview], *rect );
1588 NSSize offset = NSMakeSize((float)dx, (float)dy);
1589 [m_osxView scrollRect:r by:offset];
1593 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
1595 wxWindowMac* parent = GetWXPeer()->GetParent();
1596 // under Cocoa we might have a contentView in the wxParent to which we have to
1597 // adjust the coordinates
1598 if (parent && [m_osxView superview] != parent->GetHandle() )
1600 int cx = 0,cy = 0,cw = 0,ch = 0;
1601 if ( parent->GetPeer() )
1603 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
1608 [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
1609 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
1610 [m_osxView setFrame:r];
1611 [[m_osxView superview] setNeedsDisplayInRect:r];
1613 wxNSView* wxview = (wxNSView*)m_osxView;
1614 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
1615 if ([wxview respondsToSelector:@selector(updateTrackingArea)] )
1616 [wxview updateTrackingArea];
1618 if ([m_osxView respondsToSelector:@selector(trackingTag)] )
1620 if ( [wxview trackingTag] )
1621 [wxview removeTrackingRect: [wxview trackingTag]];
1623 [wxview setTrackingTag: [wxview addTrackingRect: [m_osxView bounds] owner: wxview userData: nil assumeInside: NO]];
1628 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
1630 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
1635 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
1637 NSRect rect = [m_osxView frame];
1638 width = (int)rect.size.width;
1639 height = (int)rect.size.height;
1642 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
1644 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
1646 NSView* cv = [m_osxView contentView];
1648 NSRect bounds = [m_osxView bounds];
1649 NSRect rect = [cv frame];
1651 int y = (int)rect.origin.y;
1652 int x = (int)rect.origin.x;
1653 if ( ![ m_osxView isFlipped ] )
1654 y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
1657 width = (int)rect.size.width;
1658 height = (int)rect.size.height;
1663 GetSize( width, height );
1667 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
1670 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
1672 [m_osxView setNeedsDisplay:YES];
1675 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
1677 return [m_osxView needsDisplay];
1680 bool wxWidgetCocoaImpl::CanFocus() const
1682 return [m_osxView canBecomeKeyView] == YES;
1685 bool wxWidgetCocoaImpl::HasFocus() const
1687 return ( FindFocus() == m_osxView );
1690 bool wxWidgetCocoaImpl::SetFocus()
1695 [[m_osxView window] makeKeyAndOrderFront:nil] ;
1696 [[m_osxView window] makeFirstResponder: m_osxView] ;
1701 void wxWidgetCocoaImpl::RemoveFromParent()
1703 [m_osxView removeFromSuperview];
1706 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
1708 NSView* container = parent->GetWXWidget() ;
1709 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
1710 [container addSubview:m_osxView];
1713 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
1715 NSView* targetView = m_osxView;
1716 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
1717 targetView = [(NSScrollView*) m_osxView documentView];
1719 if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
1721 [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
1722 green:(CGFloat) (col.Green() / 255.0)
1723 blue:(CGFloat) (col.Blue() / 255.0)
1724 alpha:(CGFloat) (col.Alpha() / 255.0)]];
1728 bool wxWidgetCocoaImpl::SetBackgroundStyle( wxBackgroundStyle style )
1730 BOOL opaque = ( style == wxBG_STYLE_PAINT );
1732 if ( [m_osxView respondsToSelector:@selector(setOpaque:) ] )
1734 [m_osxView setOpaque: opaque];
1740 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
1742 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
1744 wxCFStringRef cf( title , encoding );
1745 [m_osxView setTitle:cf.AsNSString()];
1747 else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
1749 wxCFStringRef cf( title , encoding );
1750 [m_osxView setStringValue:cf.AsNSString()];
1755 void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
1757 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
1758 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
1759 *pt = wxFromNSPoint( to->GetWXWidget(), p );
1762 wxInt32 wxWidgetCocoaImpl::GetValue() const
1764 return [(NSControl*)m_osxView intValue];
1767 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
1769 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
1771 [m_osxView setIntValue:v];
1773 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
1775 [m_osxView setFloatValue:(double)v];
1777 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
1779 [m_osxView setDoubleValue:(double)v];
1783 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
1785 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
1787 [m_osxView setMinValue:(double)v];
1791 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
1793 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
1795 [m_osxView setMaxValue:(double)v];
1799 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
1801 if ( [m_osxView respondsToSelector:@selector(getMinValue:)] )
1803 return (int)[m_osxView minValue];
1808 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
1810 if ( [m_osxView respondsToSelector:@selector(getMaxValue:)] )
1812 return (int)[m_osxView maxValue];
1817 wxBitmap wxWidgetCocoaImpl::GetBitmap() const
1821 // TODO: how to create a wxBitmap from NSImage?
1823 if ( [m_osxView respondsToSelector:@selector(image:)] )
1824 bmp = [m_osxView image];
1830 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
1832 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
1834 [m_osxView setImage:bitmap.GetNSImage()];
1835 [m_osxView setNeedsDisplay:YES];
1839 void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
1841 if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
1843 NSCellImagePosition pos;
1863 wxFAIL_MSG( "invalid image position" );
1867 [m_osxView setImagePosition:pos];
1871 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
1873 // implementation in subclass
1876 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
1878 r->x = r->y = r->width = r->height = 0;
1880 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
1882 NSRect former = [m_osxView frame];
1883 [m_osxView sizeToFit];
1884 NSRect best = [m_osxView frame];
1885 [m_osxView setFrame:former];
1886 r->width = (int)best.size.width;
1887 r->height = (int)best.size.height;
1891 bool wxWidgetCocoaImpl::IsEnabled() const
1893 if ( [m_osxView respondsToSelector:@selector(isEnabled) ] )
1894 return [m_osxView isEnabled];
1898 void wxWidgetCocoaImpl::Enable( bool enable )
1900 if ( [m_osxView respondsToSelector:@selector(setEnabled:) ] )
1901 [m_osxView setEnabled:enable];
1904 void wxWidgetCocoaImpl::PulseGauge()
1908 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
1912 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
1914 NSControlSize size = NSRegularControlSize;
1918 case wxWINDOW_VARIANT_NORMAL :
1919 size = NSRegularControlSize;
1922 case wxWINDOW_VARIANT_SMALL :
1923 size = NSSmallControlSize;
1926 case wxWINDOW_VARIANT_MINI :
1927 size = NSMiniControlSize;
1930 case wxWINDOW_VARIANT_LARGE :
1931 size = NSRegularControlSize;
1935 wxFAIL_MSG(wxT("unexpected window variant"));
1938 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
1939 [m_osxView setControlSize:size];
1940 else if ([m_osxView respondsToSelector:@selector(cell)])
1942 id cell = [(id)m_osxView cell];
1943 if ([cell respondsToSelector:@selector(setControlSize:)])
1944 [cell setControlSize:size];
1948 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&col, long, bool)
1950 if ([m_osxView respondsToSelector:@selector(setFont:)])
1951 [m_osxView setFont: font.OSXGetNSFont()];
1952 if ([m_osxView respondsToSelector:@selector(setTextColor:)])
1953 [m_osxView setTextColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
1954 green:(CGFloat) (col.Green() / 255.0)
1955 blue:(CGFloat) (col.Blue() / 255.0)
1956 alpha:(CGFloat) (col.Alpha() / 255.0)]];
1959 void wxWidgetCocoaImpl::SetToolTip(wxToolTip* tooltip)
1963 wxCFStringRef cf( tooltip->GetTip() , m_wxPeer->GetFont().GetEncoding() );
1964 [m_osxView setToolTip: cf.AsNSString()];
1967 [m_osxView setToolTip: nil];
1971 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
1973 WXWidget c = control ? control : (WXWidget) m_osxView;
1974 wxWidgetImpl::Associate( c, this ) ;
1975 if ([c respondsToSelector:@selector(setAction:)])
1978 [c setAction: @selector(controlAction:)];
1979 if ([c respondsToSelector:@selector(setDoubleAction:)])
1981 [c setDoubleAction: @selector(controlDoubleAction:)];
1987 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
1989 wxKeyEvent wxevent(wxEVT_CHAR);
1990 SetupKeyEvent( wxevent, event, text );
1992 return GetWXPeer()->OSXHandleKeyEvent(wxevent);
1995 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
1997 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1998 SetupKeyEvent( wxevent, event );
1999 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
2001 // this will fire higher level events, like insertText, to help
2002 // us handle EVT_CHAR, etc.
2004 if ( m_wxPeer->MacIsUserPane() && [event type] == NSKeyDown)
2008 if ( wxevent.GetKeyCode() < WXK_SPACE || wxevent.GetKeyCode() == WXK_DELETE || wxevent.GetKeyCode() >= WXK_START )
2010 // eventually we could setup a doCommandBySelector catcher and retransform this into the wx key chars
2011 wxKeyEvent wxevent2(wxevent) ;
2012 wxevent2.SetEventType(wxEVT_CHAR);
2013 GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2017 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2018 [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
2020 [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
2029 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
2031 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
2032 SetupMouseEvent(wxevent , event) ;
2034 return GetWXPeer()->HandleWindowEvent(wxevent);
2037 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
2039 wxWindow* thisWindow = GetWXPeer();
2040 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
2042 thisWindow->MacInvalidateBorders();
2045 if ( receivedFocus )
2047 wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
2048 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
2049 thisWindow->HandleWindowEvent(eventFocus);
2052 if ( thisWindow->GetCaret() )
2053 thisWindow->GetCaret()->OnSetFocus();
2056 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
2057 event.SetEventObject(thisWindow);
2059 event.SetWindow(otherWindow->GetWXPeer());
2060 thisWindow->HandleWindowEvent(event) ;
2062 else // !receivedFocuss
2065 if ( thisWindow->GetCaret() )
2066 thisWindow->GetCaret()->OnKillFocus();
2069 wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
2071 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
2072 event.SetEventObject(thisWindow);
2074 event.SetWindow(otherWindow->GetWXPeer());
2075 thisWindow->HandleWindowEvent(event) ;
2079 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
2081 NSPoint location = [NSEvent mouseLocation];
2082 location = [[m_osxView window] convertScreenToBase:location];
2083 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
2085 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
2087 [(NSCursor*)cursor.GetHCURSOR() set];
2089 [[m_osxView window] invalidateCursorRectsForView:m_osxView];
2092 void wxWidgetCocoaImpl::CaptureMouse()
2094 [[m_osxView window] disableCursorRects];
2097 void wxWidgetCocoaImpl::ReleaseMouse()
2099 [[m_osxView window] enableCursorRects];
2102 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
2104 m_isFlipped = flipped;
2111 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
2112 wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
2113 long WXUNUSED(style), long WXUNUSED(extraStyle))
2115 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
2116 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
2118 // temporary hook for dnd
2119 [v registerForDraggedTypes:[NSArray arrayWithObjects:
2120 NSStringPboardType, NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSPDFPboardType, nil]];
2122 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v );
2126 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
2128 NSWindow* tlw = now->GetWXWindow();
2130 wxWidgetCocoaImpl* c = NULL;
2131 if ( now->IsNativeWindowWrapper() )
2133 NSView* cv = [tlw contentView];
2134 c = new wxWidgetCocoaImpl( now, cv, true );
2135 // increase ref count, because the impl destructor will decrement it again
2137 if ( !now->IsShown() )
2143 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2144 c = new wxWidgetCocoaImpl( now, v, true );
2145 c->InstallEventHandler();
2146 [tlw setContentView:v];