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"
21 #include "wx/osx/private.h"
28 #if wxUSE_DRAG_AND_DROP
32 #include <objc/objc-runtime.h>
34 NSRect wxOSXGetFrameForControl( wxWindowMac* window , const wxPoint& pos , const wxSize &size , bool adjustForOrigin )
38 window->MacGetBoundsForControl( pos , size , x , y, w, h , adjustForOrigin ) ;
39 wxRect bounds(x,y,w,h);
40 NSView* sv = (window->GetParent()->GetHandle() );
42 return wxToNSRect( sv, bounds );
45 @interface wxNSView : NSView
47 NSTrackingRectTag rectTag;
50 - (BOOL) canBecomeKeyView;
51 // the tracking tag is needed to track mouse enter / exit events
52 - (void) setTrackingTag: (NSTrackingRectTag)tag;
53 - (NSTrackingRectTag) trackingTag;
56 @interface NSView(PossibleMethods)
57 - (void)setTitle:(NSString *)aString;
58 - (void)setStringValue:(NSString *)aString;
59 - (void)setIntValue:(int)anInt;
60 - (void)setFloatValue:(float)aFloat;
61 - (void)setDoubleValue:(double)aDouble;
65 - (void)setMinValue:(double)aDouble;
66 - (void)setMaxValue:(double)aDouble;
71 - (void)setEnabled:(BOOL)flag;
73 - (void)setImage:(NSImage *)image;
74 - (void)setControlSize:(NSControlSize)size;
78 - (void)setTarget:(id)anObject;
79 - (void)setAction:(SEL)aSelector;
80 - (void)setDoubleAction:(SEL)aSelector;
83 long wxOSXTranslateCocoaKey( NSEvent* event )
87 if ([event type] != NSFlagsChanged)
89 NSString* s = [event charactersIgnoringModifiers];
90 // backspace char reports as delete w/modifiers for some reason
93 switch ( [s characterAtIndex:0] )
100 case NSUpArrowFunctionKey :
103 case NSDownArrowFunctionKey :
106 case NSLeftArrowFunctionKey :
109 case NSRightArrowFunctionKey :
112 case NSInsertFunctionKey :
115 case NSDeleteFunctionKey :
118 case NSHomeFunctionKey :
121 // case NSBeginFunctionKey :
122 // retval = WXK_BEGIN;
124 case NSEndFunctionKey :
127 case NSPageUpFunctionKey :
130 case NSPageDownFunctionKey :
131 retval = WXK_PAGEDOWN;
133 case NSHelpFunctionKey :
137 int intchar = [s characterAtIndex: 0];
138 if ( intchar >= NSF1FunctionKey && intchar <= NSF24FunctionKey )
139 retval = WXK_F1 + (intchar - NSF1FunctionKey );
145 // Some keys don't seem to have constants. The code mimics the approach
146 // taken by WebKit. See:
147 // http://trac.webkit.org/browser/trunk/WebCore/platform/mac/KeyEventMac.mm
148 switch( [event keyCode] )
153 retval = WXK_COMMAND;
157 retval = WXK_CAPITAL;
160 case 56: // Left Shift
161 case 60: // Right Shift
166 case 61: // Right Alt
170 case 59: // Left Ctrl
171 case 62: // Right Ctrl
172 retval = WXK_CONTROL;
189 void SetupKeyEvent( wxKeyEvent &wxevent , NSEvent * nsEvent, NSString* charString = NULL )
191 UInt32 modifiers = [nsEvent modifierFlags] ;
192 int eventType = [nsEvent type];
194 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
195 wxevent.m_controlDown = modifiers & NSControlKeyMask;
196 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
197 wxevent.m_metaDown = modifiers & NSCommandKeyMask;
199 wxevent.m_rawCode = [nsEvent keyCode];
200 wxevent.m_rawFlags = modifiers;
202 wxevent.SetTimestamp( [nsEvent timestamp] * 1000.0 ) ;
206 wxevent.SetEventType( wxEVT_KEY_DOWN ) ;
209 wxevent.SetEventType( wxEVT_KEY_UP ) ;
211 case NSFlagsChanged :
212 // setup common code here
219 if ( eventType != NSFlagsChanged )
221 NSString* nschars = [nsEvent characters];
224 // if charString is set, it did not come from key up / key down
225 wxevent.SetEventType( wxEVT_CHAR );
226 wxCFStringRef cfchars((CFStringRef)[charString retain]);
227 chars = cfchars.AsString();
231 wxCFStringRef cfchars((CFStringRef)[nschars retain]);
232 chars = cfchars.AsString();
236 int aunichar = chars.Length() > 0 ? chars[0] : 0;
239 if (wxevent.GetEventType() != wxEVT_CHAR)
240 keyval = wxOSXTranslateCocoaKey(nsEvent) ;
244 if ( wxevent.GetEventType() == wxEVT_KEY_UP || wxevent.GetEventType() == wxEVT_KEY_DOWN )
245 keyval = wxToupper( aunichar ) ;
251 wxevent.m_uniChar = aunichar;
253 wxevent.m_keyCode = keyval;
256 UInt32 g_lastButton = 0 ;
257 bool g_lastButtonWasFakeRight = false ;
259 void SetupMouseEvent( wxMouseEvent &wxevent , NSEvent * nsEvent )
261 int eventType = [nsEvent type];
262 UInt32 modifiers = [nsEvent modifierFlags] ;
263 wxPoint screenMouseLocation = wxFromNSPoint( NULL, [nsEvent locationInWindow]);
265 // these parameters are not given for all events
266 UInt32 button = [nsEvent buttonNumber];
267 UInt32 clickCount = 0;
269 wxevent.m_x = screenMouseLocation.x;
270 wxevent.m_y = screenMouseLocation.y;
271 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
272 wxevent.m_controlDown = modifiers & NSControlKeyMask;
273 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
274 wxevent.m_metaDown = modifiers & NSCommandKeyMask;
275 wxevent.SetTimestamp( [nsEvent timestamp] * 1000.0 ) ;
277 UInt32 mouseChord = 0;
281 case NSLeftMouseDown :
282 case NSLeftMouseDragged :
285 case NSRightMouseDown :
286 case NSRightMouseDragged :
289 case NSOtherMouseDown :
290 case NSOtherMouseDragged :
295 // a control click is interpreted as a right click
296 bool thisButtonIsFakeRight = false ;
297 if ( button == 0 && (modifiers & NSControlKeyMask) )
300 thisButtonIsFakeRight = true ;
303 // otherwise we report double clicks by connecting a left click with a ctrl-left click
304 if ( clickCount > 1 && button != g_lastButton )
307 // we must make sure that our synthetic 'right' button corresponds in
308 // mouse down, moved and mouse up, and does not deliver a right down and left up
311 case NSLeftMouseDown :
312 case NSRightMouseDown :
313 case NSOtherMouseDown :
314 g_lastButton = button ;
315 g_lastButtonWasFakeRight = thisButtonIsFakeRight ;
322 g_lastButtonWasFakeRight = false ;
324 else if ( g_lastButton == 1 && g_lastButtonWasFakeRight )
325 button = g_lastButton ;
327 // Adjust the chord mask to remove the primary button and add the
328 // secondary button. It is possible that the secondary button is
329 // already pressed, e.g. on a mouse connected to a laptop, but this
330 // possibility is ignored here:
331 if( thisButtonIsFakeRight && ( mouseChord & 1U ) )
332 mouseChord = ((mouseChord & ~1U) | 2U);
335 wxevent.m_leftDown = true ;
337 wxevent.m_rightDown = true ;
339 wxevent.m_middleDown = true ;
341 // translate into wx types
344 case NSLeftMouseDown :
345 case NSRightMouseDown :
346 case NSOtherMouseDown :
347 clickCount = [nsEvent clickCount];
351 wxevent.SetEventType( clickCount > 1 ? wxEVT_LEFT_DCLICK : wxEVT_LEFT_DOWN ) ;
355 wxevent.SetEventType( clickCount > 1 ? wxEVT_RIGHT_DCLICK : wxEVT_RIGHT_DOWN ) ;
359 wxevent.SetEventType( clickCount > 1 ? wxEVT_MIDDLE_DCLICK : wxEVT_MIDDLE_DOWN ) ;
368 case NSRightMouseUp :
369 case NSOtherMouseUp :
370 clickCount = [nsEvent clickCount];
374 wxevent.SetEventType( wxEVT_LEFT_UP ) ;
378 wxevent.SetEventType( wxEVT_RIGHT_UP ) ;
382 wxevent.SetEventType( wxEVT_MIDDLE_UP ) ;
392 wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ;
393 wxevent.m_wheelDelta = 10;
394 wxevent.m_linesPerAction = 1;
395 NSLog(@"deltaX %f, deltaY %f",[nsEvent deltaX], [nsEvent deltaY]);
396 if ( abs([nsEvent deltaX]) > abs([nsEvent deltaY]) )
398 wxevent.m_wheelAxis = 1;
399 wxevent.m_wheelRotation = [nsEvent deltaX] * 10.0;
403 wxevent.m_wheelRotation = [nsEvent deltaY] * 10.0;
408 case NSMouseEntered :
409 wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
412 wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
414 case NSLeftMouseDragged :
415 case NSRightMouseDragged :
416 case NSOtherMouseDragged :
418 wxevent.SetEventType( wxEVT_MOTION ) ;
424 wxevent.m_clickCount = clickCount;
428 @implementation wxNSView
432 static BOOL initialized = NO;
436 wxOSXCocoaClassAddWXMethods( self );
440 - (BOOL) canBecomeKeyView
445 - (void) setTrackingTag: (NSTrackingRectTag)tag
450 - (NSTrackingRectTag) trackingTag
461 #if wxUSE_DRAG_AND_DROP
463 // see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
464 // for details on the NSPasteboard -> PasteboardRef conversion
466 NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
468 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
470 return NSDragOperationNone;
472 return impl->draggingEntered(sender, self, _cmd);
475 void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
477 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
481 return impl->draggingExited(sender, self, _cmd);
484 NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
486 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
488 return NSDragOperationNone;
490 return impl->draggingUpdated(sender, self, _cmd);
493 BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
495 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
497 return NSDragOperationNone;
499 return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
502 void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
504 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
508 impl->mouseEvent(event, self, _cmd);
511 void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
513 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
517 impl->keyEvent(event, self, _cmd);
520 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
522 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
526 impl->insertText(text, self, _cmd);
529 BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
531 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
535 return impl->performKeyEquivalent(event, self, _cmd);
538 BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
540 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
544 return impl->acceptsFirstResponder(self, _cmd);
547 BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
549 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
553 return impl->becomeFirstResponder(self, _cmd);
556 BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
558 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
562 return impl->resignFirstResponder(self, _cmd);
565 void wxOSX_resetCursorRects(NSView* self, SEL _cmd)
567 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
571 impl->resetCursorRects(self, _cmd);
574 BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
576 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
580 return impl->isFlipped(self, _cmd) ? YES:NO;
583 void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
585 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
589 return impl->drawRect(&rect, self, _cmd);
592 void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
594 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
598 impl->controlAction(self, _cmd, sender);
601 void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
603 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
607 impl->controlDoubleAction(self, _cmd, sender);
610 unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget slf, void *_cmd)
612 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
613 NSPasteboard *pboard = [sender draggingPasteboard];
614 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
616 wxWindow* wxpeer = GetWXPeer();
617 if ( wxpeer == NULL )
618 return NSDragOperationNone;
620 wxDropTarget* target = wxpeer->GetDropTarget();
621 if ( target == NULL )
622 return NSDragOperationNone;
624 wxDragResult result = wxDragNone;
625 wxPoint pt = wxFromNSPoint( m_osxView, [sender draggingLocation] );
627 if ( sourceDragMask & NSDragOperationLink )
629 else if ( sourceDragMask & NSDragOperationCopy )
631 else if ( sourceDragMask & NSDragOperationMove )
634 PasteboardRef pboardRef;
635 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
636 target->SetCurrentDragPasteboard(pboardRef);
637 result = target->OnEnter(pt.x, pt.y, result);
638 CFRelease(pboardRef);
640 NSDragOperation nsresult = NSDragOperationNone;
644 nsresult = NSDragOperationLink;
646 nsresult = NSDragOperationMove;
648 nsresult = NSDragOperationCopy;
655 void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget slf, void *_cmd)
657 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
658 NSPasteboard *pboard = [sender draggingPasteboard];
660 wxWindow* wxpeer = GetWXPeer();
661 if ( wxpeer == NULL )
664 wxDropTarget* target = wxpeer->GetDropTarget();
665 if ( target == NULL )
668 PasteboardRef pboardRef;
669 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
670 target->SetCurrentDragPasteboard(pboardRef);
672 CFRelease(pboardRef);
675 unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget slf, void *_cmd)
677 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
678 NSPasteboard *pboard = [sender draggingPasteboard];
679 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
681 wxWindow* wxpeer = GetWXPeer();
682 if ( wxpeer == NULL )
683 return NSDragOperationNone;
685 wxDropTarget* target = wxpeer->GetDropTarget();
686 if ( target == NULL )
687 return NSDragOperationNone;
689 wxDragResult result = wxDragNone;
690 wxPoint pt = wxFromNSPoint( m_osxView, [sender draggingLocation] );
692 if ( sourceDragMask & NSDragOperationLink )
694 else if ( sourceDragMask & NSDragOperationCopy )
696 else if ( sourceDragMask & NSDragOperationMove )
699 PasteboardRef pboardRef;
700 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
701 target->SetCurrentDragPasteboard(pboardRef);
702 result = target->OnDragOver(pt.x, pt.y, result);
703 CFRelease(pboardRef);
705 NSDragOperation nsresult = NSDragOperationNone;
709 nsresult = NSDragOperationLink;
711 nsresult = NSDragOperationMove;
713 nsresult = NSDragOperationCopy;
720 bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget slf, void *_cmd)
722 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
724 NSPasteboard *pboard = [sender draggingPasteboard];
725 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
727 wxWindow* wxpeer = GetWXPeer();
728 wxDropTarget* target = wxpeer->GetDropTarget();
729 wxDragResult result = wxDragNone;
730 wxPoint pt = wxFromNSPoint( m_osxView, [sender draggingLocation] );
732 if ( sourceDragMask & NSDragOperationLink )
734 else if ( sourceDragMask & NSDragOperationCopy )
736 else if ( sourceDragMask & NSDragOperationMove )
739 PasteboardRef pboardRef;
740 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
741 target->SetCurrentDragPasteboard(pboardRef);
742 result = target->OnData(pt.x, pt.y, result);
743 CFRelease(pboardRef);
745 return result != wxDragNone;
750 typedef void (*wxOSX_TextEventHandlerPtr)(NSView* self, SEL _cmd, NSString *event);
751 typedef void (*wxOSX_EventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
752 typedef BOOL (*wxOSX_PerformKeyEventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
753 typedef BOOL (*wxOSX_FocusHandlerPtr)(NSView* self, SEL _cmd);
754 typedef BOOL (*wxOSX_ResetCursorRectsHandlerPtr)(NSView* self, SEL _cmd);
755 typedef BOOL (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
757 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
759 if ( !DoHandleMouseEvent(event) )
761 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
762 superimpl(slf, (SEL)_cmd, event);
766 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
768 if ( [[slf window] firstResponder] != slf || !DoHandleKeyEvent(event) )
770 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
771 superimpl(slf, (SEL)_cmd, event);
775 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
777 if (m_lastKeyDownEvent && !DoHandleCharEvent(m_lastKeyDownEvent, text) )
779 wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
780 superimpl(slf, (SEL)_cmd, text);
782 m_lastKeyDownEvent = NULL;
786 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
788 wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
789 return superimpl(slf, (SEL)_cmd, event);
792 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
794 // FIXME: We need to find a way to query AcceptsFocus here, but when we do it
795 // it calls native APIs which lead us back here and into a loop.
796 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
797 return superimpl(slf, (SEL)_cmd);
800 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
802 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
803 // get the current focus before running becomeFirstResponder
804 NSView* otherView = [[NSApp keyWindow] firstResponder];
805 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
806 BOOL r = superimpl(slf, (SEL)_cmd);
808 DoNotifyFocusEvent( true, otherWindow );
812 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
814 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
815 BOOL r = superimpl(slf, (SEL)_cmd);
816 // get the current focus after running resignFirstResponder
817 NSView* otherView = [[NSApp keyWindow] firstResponder];
818 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
820 DoNotifyFocusEvent( false, otherWindow );
824 void wxWidgetCocoaImpl::resetCursorRects(WXWidget slf, void *_cmd)
826 wxWindow* wxpeer = GetWXPeer();
829 NSCursor *cursor = (NSCursor*)wxpeer->GetCursor().GetHCURSOR();
832 wxOSX_ResetCursorRectsHandlerPtr superimpl = (wxOSX_ResetCursorRectsHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
833 superimpl(slf, (SEL)_cmd);
837 [slf addCursorRect: [slf bounds]
843 bool wxWidgetCocoaImpl::isFlipped(WXWidget slf, void *_cmd)
849 #define OSX_DEBUG_DRAWING 0
851 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *_cmd)
853 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
854 CGContextSaveGState( context );
856 #if OSX_DEBUG_DRAWING
857 CGContextBeginPath( context );
858 CGContextMoveToPoint(context, 0, 0);
859 NSRect bounds = [self bounds];
860 CGContextAddLineToPoint(context, 10, 0);
861 CGContextMoveToPoint(context, 0, 0);
862 CGContextAddLineToPoint(context, 0, 10);
863 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
864 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
865 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
866 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
867 CGContextClosePath( context );
868 CGContextStrokePath(context);
873 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
874 CGContextScaleCTM( context, 1, -1 );
881 [slf getRectsBeingDrawn:&rects count:&count];
882 for ( int i = 0 ; i < count ; ++i )
884 updateRgn.Union(wxFromNSRect(slf, rects[i]) );
887 wxWindow* wxpeer = GetWXPeer();
888 wxpeer->GetUpdateRegion() = updateRgn;
889 wxpeer->MacSetCGContextRef( context );
891 bool handled = wxpeer->MacDoRedraw( 0 );
893 CGContextRestoreGState( context );
895 CGContextSaveGState( context );
899 SEL _cmd = @selector(drawRect:);
900 wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
901 superimpl(slf, _cmd, *(NSRect*)rect);
902 CGContextRestoreGState( context );
903 CGContextSaveGState( context );
905 wxpeer->MacPaintChildrenBorders();
906 wxpeer->MacSetCGContextRef( NULL );
907 CGContextRestoreGState( context );
910 void wxWidgetCocoaImpl::controlAction( WXWidget slf, void *_cmd, void *sender)
912 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
914 wxpeer->OSXHandleClicked(0);
917 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget slf, void *_cmd, void *sender)
923 #if OBJC_API_VERSION >= 2
925 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
926 class_addMethod(c, s, i, t );
930 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
935 void wxOSXCocoaClassAddWXMethods(Class c)
938 #if OBJC_API_VERSION < 2
939 static objc_method wxmethods[] =
943 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
944 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
945 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
947 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
948 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
949 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
951 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
953 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
954 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
955 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
957 wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
958 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
959 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
961 wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
962 wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
963 wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
965 wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
967 wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "v@:@" )
969 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
970 wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
971 wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
972 wxOSX_CLASS_ADD_METHOD(c, @selector(resetCursorRects), (IMP) wxOSX_resetCursorRects, "v@:" )
974 wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
975 wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
977 wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
978 wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
980 #if wxUSE_DRAG_AND_DROP
981 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
982 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
983 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
984 wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
987 #if OBJC_API_VERSION < 2
989 static int method_count = WXSIZEOF( wxmethods );
990 static objc_method_list *wxmethodlist = NULL;
991 if ( wxmethodlist == NULL )
993 wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
994 memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
995 wxmethodlist->method_count = method_count;
996 wxmethodlist->obsolete = 0;
998 class_addMethods( c, wxmethodlist );
1003 // C++ implementation class
1006 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1008 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl ) :
1009 wxWidgetImpl( peer, isRootControl )
1015 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1020 void wxWidgetCocoaImpl::Init()
1024 m_lastKeyDownEvent = NULL;
1027 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1029 RemoveAssociations( this );
1031 if ( !IsRootControl() )
1033 NSView *sv = [m_osxView superview];
1035 [m_osxView removeFromSuperview];
1037 [m_osxView release];
1040 bool wxWidgetCocoaImpl::IsVisible() const
1042 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1045 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1047 [m_osxView setHidden:(visible ? NO:YES)];
1050 void wxWidgetCocoaImpl::Raise()
1054 void wxWidgetCocoaImpl::Lower()
1058 void wxWidgetCocoaImpl::ScrollRect( const wxRect *rect, int dx, int dy )
1063 // We should do something like this, but it wasn't working in 10.4.
1064 if (GetNeedsDisplay() )
1068 NSRect r = wxToNSRect( [m_osxView superview], *rect );
1069 NSSize offset = NSMakeSize((float)dx, (float)dy);
1070 [m_osxView scrollRect:r by:offset];
1074 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
1076 wxWindowMac* parent = GetWXPeer()->GetParent();
1077 // under Cocoa we might have a contentView in the wxParent to which we have to
1078 // adjust the coordinates
1081 int cx = 0,cy = 0,cw = 0,ch = 0;
1082 if ( parent->GetPeer() )
1084 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
1089 [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
1090 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
1091 [m_osxView setFrame:r];
1092 [[m_osxView superview] setNeedsDisplayInRect:r];
1094 if ([m_osxView respondsToSelector:@selector(trackingTag)] )
1096 if ( [(wxNSView*)m_osxView trackingTag] )
1097 [m_osxView removeTrackingRect: [(wxNSView*)m_osxView trackingTag]];
1099 [(wxNSView*)m_osxView setTrackingTag: [m_osxView addTrackingRect: [m_osxView bounds] owner: m_osxView userData: nil assumeInside: NO]];
1103 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
1105 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
1110 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
1112 NSRect rect = [m_osxView frame];
1113 width = rect.size.width;
1114 height = rect.size.height;
1117 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
1119 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
1121 NSView* cv = [m_osxView contentView];
1123 NSRect bounds = [m_osxView bounds];
1124 NSRect rect = [cv frame];
1126 int y = rect.origin.y;
1127 int x = rect.origin.x;
1128 if ( ![ m_osxView isFlipped ] )
1129 y = bounds.size.height - (rect.origin.y + rect.size.height);
1132 width = rect.size.width;
1133 height = rect.size.height;
1138 GetSize( width, height );
1142 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
1145 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
1147 [m_osxView setNeedsDisplay:YES];
1150 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
1152 return [m_osxView needsDisplay];
1155 bool wxWidgetCocoaImpl::CanFocus() const
1157 return [m_osxView canBecomeKeyView] == YES;
1160 bool wxWidgetCocoaImpl::HasFocus() const
1162 return ( [[m_osxView window] firstResponder] == m_osxView );
1165 bool wxWidgetCocoaImpl::SetFocus()
1167 if ( [m_osxView canBecomeKeyView] == NO )
1170 [[m_osxView window] makeFirstResponder: m_osxView] ;
1175 void wxWidgetCocoaImpl::RemoveFromParent()
1177 [m_osxView removeFromSuperview];
1180 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
1182 NSView* container = parent->GetWXWidget() ;
1183 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
1184 [container addSubview:m_osxView];
1187 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &WXUNUSED(col) )
1189 // m_osxView.backgroundColor = [[UIColor alloc] initWithCGColor:col.GetCGColor()];
1192 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
1194 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
1196 wxCFStringRef cf( title , m_wxPeer->GetFont().GetEncoding() );
1197 [m_osxView setTitle:cf.AsNSString()];
1199 else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
1201 wxCFStringRef cf( title , m_wxPeer->GetFont().GetEncoding() );
1202 [m_osxView setStringValue:cf.AsNSString()];
1207 void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
1209 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
1210 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
1211 *pt = wxFromNSPoint( to->GetWXWidget(), p );
1214 wxInt32 wxWidgetCocoaImpl::GetValue() const
1216 return [(NSControl*)m_osxView intValue];
1219 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
1221 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
1223 [m_osxView setIntValue:v];
1225 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
1227 [m_osxView setFloatValue:(double)v];
1229 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
1231 [m_osxView setDoubleValue:(double)v];
1235 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
1237 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
1239 [m_osxView setMinValue:(double)v];
1243 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
1245 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
1247 [m_osxView setMaxValue:(double)v];
1251 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
1253 if ( [m_osxView respondsToSelector:@selector(getMinValue:)] )
1255 return [m_osxView minValue];
1260 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
1262 if ( [m_osxView respondsToSelector:@selector(getMaxValue:)] )
1264 return [m_osxView maxValue];
1269 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
1271 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
1273 [m_osxView setImage:bitmap.GetNSImage()];
1277 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& notebook)
1279 // implementation in subclass
1282 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
1284 r->x = r->y = r->width = r->height = 0;
1286 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
1288 NSRect former = [m_osxView frame];
1289 [m_osxView sizeToFit];
1290 NSRect best = [m_osxView frame];
1291 [m_osxView setFrame:former];
1292 r->width = best.size.width;
1293 r->height = best.size.height;
1297 bool wxWidgetCocoaImpl::IsEnabled() const
1299 if ( [m_osxView respondsToSelector:@selector(isEnabled) ] )
1300 return [m_osxView isEnabled];
1304 void wxWidgetCocoaImpl::Enable( bool enable )
1306 if ( [m_osxView respondsToSelector:@selector(setEnabled:) ] )
1307 [m_osxView setEnabled:enable];
1310 void wxWidgetCocoaImpl::PulseGauge()
1314 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 val, wxInt32 view )
1318 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
1320 NSControlSize size = NSRegularControlSize;
1324 case wxWINDOW_VARIANT_NORMAL :
1325 size = NSRegularControlSize;
1328 case wxWINDOW_VARIANT_SMALL :
1329 size = NSSmallControlSize;
1332 case wxWINDOW_VARIANT_MINI :
1333 size = NSMiniControlSize;
1336 case wxWINDOW_VARIANT_LARGE :
1337 size = NSRegularControlSize;
1341 wxFAIL_MSG(_T("unexpected window variant"));
1344 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
1345 [m_osxView setControlSize:size];
1348 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&, long, bool)
1350 if ([m_osxView respondsToSelector:@selector(setFont:)])
1351 #if wxOSX_USE_CORE_TEXT
1352 [m_osxView setFont: (CTFontRef)font.MacGetCTFont()];
1358 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
1360 WXWidget c = control ? control : (WXWidget) m_osxView;
1361 wxWidgetImpl::Associate( c, this ) ;
1362 if ([c respondsToSelector:@selector(setAction:)])
1365 [c setAction: @selector(controlAction:)];
1366 if ([c respondsToSelector:@selector(setDoubleAction:)])
1368 [c setDoubleAction: @selector(controlDoubleAction:)];
1374 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
1376 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1377 SetupKeyEvent( wxevent, event, text );
1378 wxevent.SetEventObject(GetWXPeer());
1380 return GetWXPeer()->OSXHandleKeyEvent(wxevent);
1383 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
1385 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1386 SetupKeyEvent( wxevent, event );
1387 wxevent.SetEventObject(GetWXPeer());
1388 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
1390 // this will fire higher level events, like insertText, to help
1391 // us handle EVT_CHAR, etc.
1392 if ([event type] == NSKeyDown)
1394 m_lastKeyDownEvent = event;
1395 [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
1400 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
1402 NSPoint clickLocation;
1403 clickLocation = [m_osxView convertPoint:[event locationInWindow] fromView:nil];
1404 wxPoint pt = wxFromNSPoint( m_osxView, clickLocation );
1405 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
1406 SetupMouseEvent( wxevent , event ) ;
1407 wxevent.SetEventObject(GetWXPeer());
1411 return GetWXPeer()->HandleWindowEvent(wxevent);
1414 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
1416 wxWindow* thisWindow = GetWXPeer();
1417 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
1419 thisWindow->MacInvalidateBorders();
1422 if ( receivedFocus )
1424 wxLogTrace(_T("Focus"), _T("focus set(%p)"), static_cast<void*>(thisWindow));
1425 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
1426 thisWindow->HandleWindowEvent(eventFocus);
1429 if ( thisWindow->GetCaret() )
1430 thisWindow->GetCaret()->OnSetFocus();
1433 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
1434 event.SetEventObject(thisWindow);
1436 event.SetWindow(otherWindow->GetWXPeer());
1437 thisWindow->HandleWindowEvent(event) ;
1439 else // !receivedFocuss
1442 if ( thisWindow->GetCaret() )
1443 thisWindow->GetCaret()->OnKillFocus();
1446 wxLogTrace(_T("Focus"), _T("focus lost(%p)"), static_cast<void*>(thisWindow));
1448 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
1449 event.SetEventObject(thisWindow);
1451 event.SetWindow(otherWindow->GetWXPeer());
1452 thisWindow->HandleWindowEvent(event) ;
1456 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
1458 NSPoint location = [NSEvent mouseLocation];
1459 location = [[m_osxView window] convertScreenToBase:location];
1460 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
1462 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
1464 [(NSCursor*)cursor.GetHCURSOR() set];
1466 [[m_osxView window] invalidateCursorRectsForView:m_osxView];
1469 void wxWidgetCocoaImpl::CaptureMouse()
1471 [[m_osxView window] disableCursorRects];
1474 void wxWidgetCocoaImpl::ReleaseMouse()
1476 [[m_osxView window] enableCursorRects];
1479 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
1481 m_isFlipped = flipped;
1488 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* parent, wxWindowID id, const wxPoint& pos, const wxSize& size,
1489 long style, long extraStyle)
1491 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
1492 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
1494 // temporary hook for dnd
1495 [v registerForDraggedTypes:[NSArray arrayWithObjects:
1496 NSStringPboardType, NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSPDFPboardType, nil]];
1498 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v );
1502 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
1504 NSWindow* tlw = now->GetWXWindow();
1505 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
1506 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( now, v, true );
1507 c->InstallEventHandler();
1508 [tlw setContentView:v];