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"
24 #include "wx/evtloop.h"
30 #if wxUSE_DRAG_AND_DROP
34 #include <objc/objc-runtime.h>
36 // Get the window with the focus
38 NSView* GetViewFromResponder( NSResponder* responder )
41 if ( [responder isKindOfClass:[NSTextView class]] )
43 NSView* delegate = (NSView*) [(NSTextView*)responder delegate];
44 if ( [delegate isKindOfClass:[NSTextField class] ] )
47 view = (NSView*) responder;
51 if ( [responder isKindOfClass:[NSView class]] )
52 view = (NSView*) responder;
57 NSView* GetFocusedViewInWindow( NSWindow* keyWindow )
59 NSView* focusedView = nil;
60 if ( keyWindow != nil )
61 focusedView = GetViewFromResponder([keyWindow firstResponder]);
66 WXWidget wxWidgetImpl::FindFocus()
68 return GetFocusedViewInWindow( [[NSApplication sharedApplication] keyWindow] );
71 NSRect wxOSXGetFrameForControl( wxWindowMac* window , const wxPoint& pos , const wxSize &size , bool adjustForOrigin )
75 window->MacGetBoundsForControl( pos , size , x , y, w, h , adjustForOrigin ) ;
76 wxRect bounds(x,y,w,h);
77 NSView* sv = (window->GetParent()->GetHandle() );
79 return wxToNSRect( sv, bounds );
82 @interface wxNSView : NSView
84 NSTrackingRectTag rectTag;
85 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
86 NSTrackingArea* _trackingArea;
90 // the tracking tag is needed to track mouse enter / exit events
91 - (void) setTrackingTag: (NSTrackingRectTag)tag;
92 - (NSTrackingRectTag) trackingTag;
93 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
94 // under 10.5 we can also track mouse moved events on non-focused windows if
95 // we use the new NSTrackingArea APIs.
96 - (void) updateTrackingArea;
97 - (NSTrackingArea*) trackingArea;
101 @interface NSView(PossibleMethods)
102 - (void)setTitle:(NSString *)aString;
103 - (void)setStringValue:(NSString *)aString;
104 - (void)setIntValue:(int)anInt;
105 - (void)setFloatValue:(float)aFloat;
106 - (void)setDoubleValue:(double)aDouble;
110 - (void)setMinValue:(double)aDouble;
111 - (void)setMaxValue:(double)aDouble;
116 - (void)setEnabled:(BOOL)flag;
118 - (void)setImage:(NSImage *)image;
119 - (void)setControlSize:(NSControlSize)size;
121 - (void)setFont:(NSFont *)fontObject;
125 - (void)setTarget:(id)anObject;
126 - (void)setAction:(SEL)aSelector;
127 - (void)setDoubleAction:(SEL)aSelector;
128 - (void)setBackgroundColor:(NSColor*)aColor;
129 - (void)setImagePosition:(NSCellImagePosition)aPosition;
132 long wxOSXTranslateCocoaKey( NSEvent* event )
136 if ([event type] != NSFlagsChanged)
138 NSString* s = [event charactersIgnoringModifiers];
139 // backspace char reports as delete w/modifiers for some reason
142 switch ( [s characterAtIndex:0] )
149 case NSUpArrowFunctionKey :
152 case NSDownArrowFunctionKey :
155 case NSLeftArrowFunctionKey :
158 case NSRightArrowFunctionKey :
161 case NSInsertFunctionKey :
164 case NSDeleteFunctionKey :
167 case NSHomeFunctionKey :
170 // case NSBeginFunctionKey :
171 // retval = WXK_BEGIN;
173 case NSEndFunctionKey :
176 case NSPageUpFunctionKey :
179 case NSPageDownFunctionKey :
180 retval = WXK_PAGEDOWN;
182 case NSHelpFunctionKey :
186 int intchar = [s characterAtIndex: 0];
187 if ( intchar >= NSF1FunctionKey && intchar <= NSF24FunctionKey )
188 retval = WXK_F1 + (intchar - NSF1FunctionKey );
194 // Some keys don't seem to have constants. The code mimics the approach
195 // taken by WebKit. See:
196 // http://trac.webkit.org/browser/trunk/WebCore/platform/mac/KeyEventMac.mm
197 switch( [event keyCode] )
202 retval = WXK_COMMAND;
206 retval = WXK_CAPITAL;
209 case 56: // Left Shift
210 case 60: // Right Shift
215 case 61: // Right Alt
219 case 59: // Left Ctrl
220 case 62: // Right Ctrl
221 retval = WXK_CONTROL;
233 retval = WXK_NUMPAD_DIVIDE;
236 retval = WXK_NUMPAD_MULTIPLY;
239 retval = WXK_NUMPAD_SUBTRACT;
242 retval = WXK_NUMPAD_ADD;
245 retval = WXK_NUMPAD_ENTER;
248 retval = WXK_NUMPAD_DECIMAL;
251 retval = WXK_NUMPAD0;
254 retval = WXK_NUMPAD1;
257 retval = WXK_NUMPAD2;
260 retval = WXK_NUMPAD3;
263 retval = WXK_NUMPAD4;
266 retval = WXK_NUMPAD5;
269 retval = WXK_NUMPAD6;
272 retval = WXK_NUMPAD7;
275 retval = WXK_NUMPAD8;
278 retval = WXK_NUMPAD9;
281 //retval = [event keyCode];
287 void wxWidgetCocoaImpl::SetupKeyEvent(wxKeyEvent &wxevent , NSEvent * nsEvent, NSString* charString)
289 UInt32 modifiers = [nsEvent modifierFlags] ;
290 int eventType = [nsEvent type];
292 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
293 wxevent.m_controlDown = modifiers & NSControlKeyMask;
294 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
295 wxevent.m_metaDown = modifiers & NSCommandKeyMask;
297 wxevent.m_rawCode = [nsEvent keyCode];
298 wxevent.m_rawFlags = modifiers;
300 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
303 if ( eventType != NSFlagsChanged )
305 NSString* nschars = [nsEvent charactersIgnoringModifiers];
308 // if charString is set, it did not come from key up / key down
309 wxevent.SetEventType( wxEVT_CHAR );
310 chars = wxCFStringRef::AsString(charString);
314 chars = wxCFStringRef::AsString(nschars);
318 int aunichar = chars.Length() > 0 ? chars[0] : 0;
321 if (wxevent.GetEventType() != wxEVT_CHAR)
323 keyval = wxOSXTranslateCocoaKey(nsEvent) ;
327 wxevent.SetEventType( wxEVT_KEY_DOWN ) ;
330 wxevent.SetEventType( wxEVT_KEY_UP ) ;
332 case NSFlagsChanged :
336 wxevent.SetEventType( wxevent.m_controlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
339 wxevent.SetEventType( wxevent.m_shiftDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
342 wxevent.SetEventType( wxevent.m_altDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
345 wxevent.SetEventType( wxevent.m_metaDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
356 if ( wxevent.GetEventType() == wxEVT_KEY_UP || wxevent.GetEventType() == wxEVT_KEY_DOWN )
357 keyval = wxToupper( aunichar ) ;
363 wxevent.m_uniChar = aunichar;
365 wxevent.m_keyCode = keyval;
367 wxWindowMac* peer = GetWXPeer();
370 wxevent.SetEventObject(peer);
371 wxevent.SetId(peer->GetId()) ;
375 UInt32 g_lastButton = 0 ;
376 bool g_lastButtonWasFakeRight = false ;
378 // better scroll wheel support
379 // see http://lists.apple.com/archives/cocoa-dev/2007/Feb/msg00050.html
381 @interface NSEvent (DeviceDelta)
382 - (float)deviceDeltaX;
383 - (float)deviceDeltaY;
386 void wxWidgetCocoaImpl::SetupMouseEvent( wxMouseEvent &wxevent , NSEvent * nsEvent )
388 int eventType = [nsEvent type];
389 UInt32 modifiers = [nsEvent modifierFlags] ;
390 wxPoint screenMouseLocation = wxFromNSPoint( NULL, [nsEvent locationInWindow]);
392 // these parameters are not given for all events
393 UInt32 button = [nsEvent buttonNumber];
394 UInt32 clickCount = 0;
396 wxevent.m_x = screenMouseLocation.x;
397 wxevent.m_y = screenMouseLocation.y;
398 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
399 wxevent.m_controlDown = modifiers & NSControlKeyMask;
400 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
401 wxevent.m_metaDown = modifiers & NSCommandKeyMask;
402 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
404 UInt32 mouseChord = 0;
408 case NSLeftMouseDown :
409 case NSLeftMouseDragged :
412 case NSRightMouseDown :
413 case NSRightMouseDragged :
416 case NSOtherMouseDown :
417 case NSOtherMouseDragged :
422 // a control click is interpreted as a right click
423 bool thisButtonIsFakeRight = false ;
424 if ( button == 0 && (modifiers & NSControlKeyMask) )
427 thisButtonIsFakeRight = true ;
430 // otherwise we report double clicks by connecting a left click with a ctrl-left click
431 if ( clickCount > 1 && button != g_lastButton )
434 // we must make sure that our synthetic 'right' button corresponds in
435 // mouse down, moved and mouse up, and does not deliver a right down and left up
438 case NSLeftMouseDown :
439 case NSRightMouseDown :
440 case NSOtherMouseDown :
441 g_lastButton = button ;
442 g_lastButtonWasFakeRight = thisButtonIsFakeRight ;
449 g_lastButtonWasFakeRight = false ;
451 else if ( g_lastButton == 1 && g_lastButtonWasFakeRight )
452 button = g_lastButton ;
454 // Adjust the chord mask to remove the primary button and add the
455 // secondary button. It is possible that the secondary button is
456 // already pressed, e.g. on a mouse connected to a laptop, but this
457 // possibility is ignored here:
458 if( thisButtonIsFakeRight && ( mouseChord & 1U ) )
459 mouseChord = ((mouseChord & ~1U) | 2U);
462 wxevent.m_leftDown = true ;
464 wxevent.m_rightDown = true ;
466 wxevent.m_middleDown = true ;
468 // translate into wx types
471 case NSLeftMouseDown :
472 case NSRightMouseDown :
473 case NSOtherMouseDown :
474 clickCount = [nsEvent clickCount];
478 wxevent.SetEventType( clickCount > 1 ? wxEVT_LEFT_DCLICK : wxEVT_LEFT_DOWN ) ;
482 wxevent.SetEventType( clickCount > 1 ? wxEVT_RIGHT_DCLICK : wxEVT_RIGHT_DOWN ) ;
486 wxevent.SetEventType( clickCount > 1 ? wxEVT_MIDDLE_DCLICK : wxEVT_MIDDLE_DOWN ) ;
495 case NSRightMouseUp :
496 case NSOtherMouseUp :
497 clickCount = [nsEvent clickCount];
501 wxevent.SetEventType( wxEVT_LEFT_UP ) ;
505 wxevent.SetEventType( wxEVT_RIGHT_UP ) ;
509 wxevent.SetEventType( wxEVT_MIDDLE_UP ) ;
519 wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ;
520 wxevent.m_wheelDelta = 10;
521 wxevent.m_linesPerAction = 1;
523 if ( fabs([nsEvent deviceDeltaX]) > fabs([nsEvent deviceDeltaY]) )
525 wxevent.m_wheelAxis = 1;
526 wxevent.m_wheelRotation = (int)[nsEvent deviceDeltaX];
530 wxevent.m_wheelRotation = (int)[nsEvent deviceDeltaY];
535 case NSMouseEntered :
536 wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
539 wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
541 case NSLeftMouseDragged :
542 case NSRightMouseDragged :
543 case NSOtherMouseDragged :
545 wxevent.SetEventType( wxEVT_MOTION ) ;
551 wxevent.m_clickCount = clickCount;
552 wxWindowMac* peer = GetWXPeer();
555 wxevent.SetEventObject(peer);
556 wxevent.SetId(peer->GetId()) ;
560 @implementation wxNSView
564 static BOOL initialized = NO;
568 wxOSXCocoaClassAddWXMethods( self );
572 - (void) setTrackingTag: (NSTrackingRectTag)tag
577 - (NSTrackingRectTag) trackingTag
582 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
583 - (void) updateTrackingArea
587 [self removeTrackingArea: _trackingArea];
588 [_trackingArea release];
591 NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingMouseMoved|NSTrackingActiveAlways;
593 NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: [self bounds] options: options owner: self userInfo: nil];
594 [self addTrackingArea: area];
596 _trackingArea = area;
599 - (NSTrackingArea*) trackingArea
601 return _trackingArea;
610 #if wxUSE_DRAG_AND_DROP
612 // see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
613 // for details on the NSPasteboard -> PasteboardRef conversion
615 NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
617 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
619 return NSDragOperationNone;
621 return impl->draggingEntered(sender, self, _cmd);
624 void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
626 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
630 return impl->draggingExited(sender, self, _cmd);
633 NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
635 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
637 return NSDragOperationNone;
639 return impl->draggingUpdated(sender, self, _cmd);
642 BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
644 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
646 return NSDragOperationNone;
648 return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
653 void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
655 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
659 impl->mouseEvent(event, self, _cmd);
662 BOOL wxOSX_acceptsFirstMouse(NSView* self, SEL _cmd, NSEvent *event)
664 // This is needed to support click through, otherwise the first click on a window
665 // will not do anything unless it is the active window already.
669 void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
671 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
675 impl->keyEvent(event, self, _cmd);
678 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
680 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
684 impl->insertText(text, self, _cmd);
687 BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
689 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
693 return impl->performKeyEquivalent(event, self, _cmd);
696 BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
698 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
702 return impl->acceptsFirstResponder(self, _cmd);
705 BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
707 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
711 return impl->becomeFirstResponder(self, _cmd);
714 BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
716 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
720 return impl->resignFirstResponder(self, _cmd);
723 void wxOSX_resetCursorRects(NSView* self, SEL _cmd)
725 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
729 impl->resetCursorRects(self, _cmd);
732 BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
734 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
738 return impl->isFlipped(self, _cmd) ? YES:NO;
741 void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
743 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
747 return impl->drawRect(&rect, self, _cmd);
750 void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
752 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
756 impl->controlAction(self, _cmd, sender);
759 void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
761 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
765 impl->controlDoubleAction(self, _cmd, sender);
768 unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
770 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
771 NSPasteboard *pboard = [sender draggingPasteboard];
772 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
774 wxWindow* wxpeer = GetWXPeer();
775 if ( wxpeer == NULL )
776 return NSDragOperationNone;
778 wxDropTarget* target = wxpeer->GetDropTarget();
779 if ( target == NULL )
780 return NSDragOperationNone;
782 wxDragResult result = wxDragNone;
783 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
784 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
786 if ( sourceDragMask & NSDragOperationLink )
788 else if ( sourceDragMask & NSDragOperationCopy )
790 else if ( sourceDragMask & NSDragOperationMove )
793 PasteboardRef pboardRef;
794 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
795 target->SetCurrentDragPasteboard(pboardRef);
796 result = target->OnEnter(pt.x, pt.y, result);
797 CFRelease(pboardRef);
799 NSDragOperation nsresult = NSDragOperationNone;
803 nsresult = NSDragOperationLink;
805 nsresult = NSDragOperationMove;
807 nsresult = NSDragOperationCopy;
814 void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
816 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
817 NSPasteboard *pboard = [sender draggingPasteboard];
819 wxWindow* wxpeer = GetWXPeer();
820 if ( wxpeer == NULL )
823 wxDropTarget* target = wxpeer->GetDropTarget();
824 if ( target == NULL )
827 PasteboardRef pboardRef;
828 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
829 target->SetCurrentDragPasteboard(pboardRef);
831 CFRelease(pboardRef);
834 unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
836 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
837 NSPasteboard *pboard = [sender draggingPasteboard];
838 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
840 wxWindow* wxpeer = GetWXPeer();
841 if ( wxpeer == NULL )
842 return NSDragOperationNone;
844 wxDropTarget* target = wxpeer->GetDropTarget();
845 if ( target == NULL )
846 return NSDragOperationNone;
848 wxDragResult result = wxDragNone;
849 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
850 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
852 if ( sourceDragMask & NSDragOperationLink )
854 else if ( sourceDragMask & NSDragOperationCopy )
856 else if ( sourceDragMask & NSDragOperationMove )
859 PasteboardRef pboardRef;
860 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
861 target->SetCurrentDragPasteboard(pboardRef);
862 result = target->OnDragOver(pt.x, pt.y, result);
863 CFRelease(pboardRef);
865 NSDragOperation nsresult = NSDragOperationNone;
869 nsresult = NSDragOperationLink;
871 nsresult = NSDragOperationMove;
873 nsresult = NSDragOperationCopy;
880 bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
882 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
884 NSPasteboard *pboard = [sender draggingPasteboard];
885 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
887 wxWindow* wxpeer = GetWXPeer();
888 wxDropTarget* target = wxpeer->GetDropTarget();
889 wxDragResult result = wxDragNone;
890 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
891 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
893 if ( sourceDragMask & NSDragOperationLink )
895 else if ( sourceDragMask & NSDragOperationCopy )
897 else if ( sourceDragMask & NSDragOperationMove )
900 PasteboardRef pboardRef;
901 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
902 target->SetCurrentDragPasteboard(pboardRef);
904 if (target->OnDrop(pt.x, pt.y))
905 result = target->OnData(pt.x, pt.y, result);
907 CFRelease(pboardRef);
909 return result != wxDragNone;
912 typedef void (*wxOSX_TextEventHandlerPtr)(NSView* self, SEL _cmd, NSString *event);
913 typedef void (*wxOSX_EventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
914 typedef BOOL (*wxOSX_PerformKeyEventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
915 typedef BOOL (*wxOSX_FocusHandlerPtr)(NSView* self, SEL _cmd);
916 typedef BOOL (*wxOSX_ResetCursorRectsHandlerPtr)(NSView* self, SEL _cmd);
917 typedef void (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
919 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
921 if ( !DoHandleMouseEvent(event) )
923 // for plain NSView mouse events would propagate to parents otherwise
924 if (!m_wxPeer->MacIsUserPane())
926 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
927 superimpl(slf, (SEL)_cmd, event);
932 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
934 if ( [event type] == NSKeyDown )
935 m_lastKeyDownEvent = event;
936 if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
938 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
939 superimpl(slf, (SEL)_cmd, event);
941 m_lastKeyDownEvent = NULL;
944 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
946 if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
948 wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
949 superimpl(slf, (SEL)_cmd, text);
954 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
956 wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
957 return superimpl(slf, (SEL)_cmd, event);
960 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
962 if ( m_wxPeer->MacIsUserPane() )
963 return m_wxPeer->AcceptsFocus();
966 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
967 return superimpl(slf, (SEL)_cmd);
971 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
973 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
974 // get the current focus before running becomeFirstResponder
975 NSView* otherView = FindFocus();
977 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
978 BOOL r = superimpl(slf, (SEL)_cmd);
981 DoNotifyFocusEvent( true, otherWindow );
987 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
989 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
990 BOOL r = superimpl(slf, (SEL)_cmd);
991 // get the current focus after running resignFirstResponder
992 // note that this value isn't reliable, it might return the same view that
994 NSView* otherView = FindFocus();
995 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
996 // NSTextViews have an editor as true responder, therefore the might get the
997 // resign notification if their editor takes over, don't trigger any event then
998 if ( r && !m_hasEditor)
1000 DoNotifyFocusEvent( false, otherWindow );
1005 void wxWidgetCocoaImpl::resetCursorRects(WXWidget slf, void *_cmd)
1007 wxWindow* wxpeer = GetWXPeer();
1010 NSCursor *cursor = (NSCursor*)wxpeer->GetCursor().GetHCURSOR();
1013 wxOSX_ResetCursorRectsHandlerPtr superimpl = (wxOSX_ResetCursorRectsHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1014 superimpl(slf, (SEL)_cmd);
1018 [slf addCursorRect: [slf bounds]
1024 bool wxWidgetCocoaImpl::isFlipped(WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1030 #define OSX_DEBUG_DRAWING 0
1032 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
1034 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1035 CGContextSaveGState( context );
1037 #if OSX_DEBUG_DRAWING
1038 CGContextBeginPath( context );
1039 CGContextMoveToPoint(context, 0, 0);
1040 NSRect bounds = [self bounds];
1041 CGContextAddLineToPoint(context, 10, 0);
1042 CGContextMoveToPoint(context, 0, 0);
1043 CGContextAddLineToPoint(context, 0, 10);
1044 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1045 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1046 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1047 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1048 CGContextClosePath( context );
1049 CGContextStrokePath(context);
1054 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1055 CGContextScaleCTM( context, 1, -1 );
1059 const NSRect *rects;
1062 [slf getRectsBeingDrawn:&rects count:&count];
1063 for ( int i = 0 ; i < count ; ++i )
1065 updateRgn.Union(wxFromNSRect(slf, rects[i]) );
1068 wxWindow* wxpeer = GetWXPeer();
1069 wxpeer->GetUpdateRegion() = updateRgn;
1070 wxpeer->MacSetCGContextRef( context );
1072 bool handled = wxpeer->MacDoRedraw( 0 );
1074 CGContextRestoreGState( context );
1076 CGContextSaveGState( context );
1080 SEL _cmd = @selector(drawRect:);
1081 wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1082 superimpl(slf, _cmd, *(NSRect*)rect);
1083 CGContextRestoreGState( context );
1084 CGContextSaveGState( context );
1086 wxpeer->MacPaintChildrenBorders();
1087 wxpeer->MacSetCGContextRef( NULL );
1088 CGContextRestoreGState( context );
1091 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1093 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1095 wxpeer->OSXHandleClicked(0);
1098 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1104 #if OBJC_API_VERSION >= 2
1106 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1107 class_addMethod(c, s, i, t );
1111 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1116 void wxOSXCocoaClassAddWXMethods(Class c)
1119 #if OBJC_API_VERSION < 2
1120 static objc_method wxmethods[] =
1124 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1125 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1126 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1128 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1129 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1130 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1132 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1134 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1135 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1136 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1138 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
1140 wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1141 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1142 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1144 wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1145 wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1146 wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1148 wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1150 wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
1152 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1153 wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1154 wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1155 wxOSX_CLASS_ADD_METHOD(c, @selector(resetCursorRects), (IMP) wxOSX_resetCursorRects, "v@:" )
1157 wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1158 wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1160 wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1161 wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1163 #if wxUSE_DRAG_AND_DROP
1164 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1165 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1166 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1167 wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1170 #if OBJC_API_VERSION < 2
1172 static int method_count = WXSIZEOF( wxmethods );
1173 static objc_method_list *wxmethodlist = NULL;
1174 if ( wxmethodlist == NULL )
1176 wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1177 memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1178 wxmethodlist->method_count = method_count;
1179 wxmethodlist->obsolete = 0;
1181 class_addMethods( c, wxmethodlist );
1186 // C++ implementation class
1189 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1191 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl ) :
1192 wxWidgetImpl( peer, isRootControl )
1197 // check if the user wants to create the control initially hidden
1198 if ( !peer->IsShown() )
1199 SetVisibility(false);
1201 // gc aware handling
1203 CFRetain(m_osxView);
1204 [m_osxView release];
1207 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1212 void wxWidgetCocoaImpl::Init()
1216 m_lastKeyDownEvent = NULL;
1217 m_hasEditor = false;
1220 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1222 RemoveAssociations( this );
1224 if ( !IsRootControl() )
1226 NSView *sv = [m_osxView superview];
1228 [m_osxView removeFromSuperview];
1230 // gc aware handling
1232 CFRelease(m_osxView);
1235 bool wxWidgetCocoaImpl::IsVisible() const
1237 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1240 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1242 [m_osxView setHidden:(visible ? NO:YES)];
1245 // ----------------------------------------------------------------------------
1246 // window animation stuff
1247 // ----------------------------------------------------------------------------
1249 // define a delegate used to refresh the window during animation
1250 @interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
1256 - (id)init:(wxWindow *)win;
1260 // NSAnimationDelegate methods
1261 - (void)animationDidEnd:(NSAnimation*)animation;
1262 - (void)animation:(NSAnimation*)animation
1263 didReachProgressMark:(NSAnimationProgress)progress;
1266 @implementation wxNSAnimationDelegate
1268 - (id)init:(wxWindow *)win
1283 - (void)animation:(NSAnimation*)animation
1284 didReachProgressMark:(NSAnimationProgress)progress
1286 wxUnusedVar(animation);
1287 wxUnusedVar(progress);
1289 m_win->SendSizeEvent();
1292 - (void)animationDidEnd:(NSAnimation*)animation
1301 wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1303 wxShowEffect effect,
1306 // create the dictionary describing the animation to perform on this view
1308 viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1309 NSMutableDictionary * const
1310 dict = [NSMutableDictionary dictionaryWithCapacity:4];
1311 [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1313 // determine the start and end rectangles assuming we're hiding the window
1314 const wxRect rectOrig = win->GetRect();
1322 if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1323 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1324 effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1325 else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1326 effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1327 effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1328 else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1329 effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1330 effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1331 else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1332 effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1333 effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1338 case wxSHOW_EFFECT_ROLL_TO_LEFT:
1339 case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1343 case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1344 case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1345 rectEnd.x = rectStart.GetRight();
1349 case wxSHOW_EFFECT_ROLL_TO_TOP:
1350 case wxSHOW_EFFECT_SLIDE_TO_TOP:
1354 case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1355 case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1356 rectEnd.y = rectStart.GetBottom();
1360 case wxSHOW_EFFECT_EXPAND:
1361 rectEnd.x = rectStart.x + rectStart.width / 2;
1362 rectEnd.y = rectStart.y + rectStart.height / 2;
1367 case wxSHOW_EFFECT_BLEND:
1368 [dict setObject:(show ? NSViewAnimationFadeInEffect
1369 : NSViewAnimationFadeOutEffect)
1370 forKey:NSViewAnimationEffectKey];
1373 case wxSHOW_EFFECT_NONE:
1374 case wxSHOW_EFFECT_MAX:
1375 wxFAIL_MSG( "unexpected animation effect" );
1379 wxFAIL_MSG( "unknown animation effect" );
1385 // we need to restore it to the original rectangle instead of making it
1387 wxSwap(rectStart, rectEnd);
1389 // and as the window is currently hidden, we need to show it for the
1390 // animation to be visible at all (but don't restore it at its full
1391 // rectangle as it shouldn't appear immediately)
1392 win->SetSize(rectStart);
1396 NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1397 ? [(NSView *)viewOrWin superview]
1399 const NSRect rStart = wxToNSRect(parentView, rectStart);
1400 const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1402 [dict setObject:[NSValue valueWithRect:rStart]
1403 forKey:NSViewAnimationStartFrameKey];
1404 [dict setObject:[NSValue valueWithRect:rEnd]
1405 forKey:NSViewAnimationEndFrameKey];
1407 // create an animation using the values in the above dictionary
1408 NSViewAnimation * const
1409 anim = [[NSViewAnimation alloc]
1410 initWithViewAnimations:[NSArray arrayWithObject:dict]];
1414 // what is a good default duration? Windows uses 200ms, Web frameworks
1415 // use anything from 250ms to 1s... choose something in the middle
1419 [anim setDuration:timeout/1000.]; // duration is in seconds here
1421 // if the window being animated changes its layout depending on its size
1422 // (which is almost always the case) we need to redo it during animation
1424 // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1425 // controls in wxInfoBar visibly jump around)
1426 const int NUM_LAYOUTS = 20;
1427 for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1428 [anim addProgressMark:f];
1430 wxNSAnimationDelegate * const
1431 animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1432 [anim setDelegate:animDelegate];
1433 [anim startAnimation];
1435 // Cocoa is capable of doing animation asynchronously or even from separate
1436 // thread but wx API doesn't provide any way to be notified about the
1437 // animation end and without this we really must ensure that the window has
1438 // the expected (i.e. the same as if a simple Show() had been used) size
1439 // when we return, so block here until the animation finishes
1441 // notice that because the default animation mode is NSAnimationBlocking,
1442 // no user input events ought to be processed from here
1444 wxEventLoopGuarantor ensureEventLoopExistence;
1445 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1446 while ( ![animDelegate isDone] )
1452 // NSViewAnimation is smart enough to hide the NSView being animated at
1453 // the end but we also must ensure that it's hidden for wx too
1456 // and we must also restore its size because it isn't expected to
1457 // change just because the window was hidden
1458 win->SetSize(rectOrig);
1462 // refresh it once again after the end to ensure that everything is in
1464 win->SendSizeEvent();
1467 [anim setDelegate:nil];
1468 [animDelegate release];
1474 bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
1475 wxShowEffect effect,
1478 return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
1481 void wxWidgetCocoaImpl::Raise()
1486 void wxWidgetCocoaImpl::Lower()
1491 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
1496 // We should do something like this, but it wasn't working in 10.4.
1497 if (GetNeedsDisplay() )
1501 NSRect r = wxToNSRect( [m_osxView superview], *rect );
1502 NSSize offset = NSMakeSize((float)dx, (float)dy);
1503 [m_osxView scrollRect:r by:offset];
1507 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
1509 wxWindowMac* parent = GetWXPeer()->GetParent();
1510 // under Cocoa we might have a contentView in the wxParent to which we have to
1511 // adjust the coordinates
1512 if (parent && [m_osxView superview] != parent->GetHandle() )
1514 int cx = 0,cy = 0,cw = 0,ch = 0;
1515 if ( parent->GetPeer() )
1517 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
1522 [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
1523 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
1524 [m_osxView setFrame:r];
1525 [[m_osxView superview] setNeedsDisplayInRect:r];
1527 wxNSView* wxview = (wxNSView*)m_osxView;
1528 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
1529 if ([wxview respondsToSelector:@selector(updateTrackingArea)] )
1530 [wxview updateTrackingArea];
1532 if ([m_osxView respondsToSelector:@selector(trackingTag)] )
1534 if ( [wxview trackingTag] )
1535 [wxview removeTrackingRect: [wxview trackingTag]];
1537 [wxview setTrackingTag: [wxview addTrackingRect: [m_osxView bounds] owner: wxview userData: nil assumeInside: NO]];
1542 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
1544 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
1549 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
1551 NSRect rect = [m_osxView frame];
1552 width = (int)rect.size.width;
1553 height = (int)rect.size.height;
1556 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
1558 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
1560 NSView* cv = [m_osxView contentView];
1562 NSRect bounds = [m_osxView bounds];
1563 NSRect rect = [cv frame];
1565 int y = (int)rect.origin.y;
1566 int x = (int)rect.origin.x;
1567 if ( ![ m_osxView isFlipped ] )
1568 y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
1571 width = (int)rect.size.width;
1572 height = (int)rect.size.height;
1577 GetSize( width, height );
1581 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
1584 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
1586 [m_osxView setNeedsDisplay:YES];
1589 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
1591 return [m_osxView needsDisplay];
1594 bool wxWidgetCocoaImpl::CanFocus() const
1596 return [m_osxView canBecomeKeyView] == YES;
1599 bool wxWidgetCocoaImpl::HasFocus() const
1601 return ( FindFocus() == m_osxView );
1604 bool wxWidgetCocoaImpl::SetFocus()
1606 if ( [m_osxView canBecomeKeyView] == NO )
1609 [[m_osxView window] makeFirstResponder: m_osxView] ;
1610 [[m_osxView window] makeKeyAndOrderFront:nil] ;
1615 void wxWidgetCocoaImpl::RemoveFromParent()
1617 [m_osxView removeFromSuperview];
1620 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
1622 NSView* container = parent->GetWXWidget() ;
1623 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
1624 [container addSubview:m_osxView];
1627 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
1629 NSView* targetView = m_osxView;
1630 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
1631 targetView = [(NSScrollView*) m_osxView documentView];
1633 if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
1635 [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
1636 green:(CGFloat) (col.Green() / 255.0)
1637 blue:(CGFloat) (col.Blue() / 255.0)
1638 alpha:(CGFloat) (col.Alpha() / 255.0)]];
1642 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
1644 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
1646 wxCFStringRef cf( title , encoding );
1647 [m_osxView setTitle:cf.AsNSString()];
1649 else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
1651 wxCFStringRef cf( title , encoding );
1652 [m_osxView setStringValue:cf.AsNSString()];
1657 void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
1659 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
1660 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
1661 *pt = wxFromNSPoint( to->GetWXWidget(), p );
1664 wxInt32 wxWidgetCocoaImpl::GetValue() const
1666 return [(NSControl*)m_osxView intValue];
1669 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
1671 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
1673 [m_osxView setIntValue:v];
1675 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
1677 [m_osxView setFloatValue:(double)v];
1679 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
1681 [m_osxView setDoubleValue:(double)v];
1685 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
1687 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
1689 [m_osxView setMinValue:(double)v];
1693 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
1695 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
1697 [m_osxView setMaxValue:(double)v];
1701 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
1703 if ( [m_osxView respondsToSelector:@selector(getMinValue:)] )
1705 return (int)[m_osxView minValue];
1710 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
1712 if ( [m_osxView respondsToSelector:@selector(getMaxValue:)] )
1714 return (int)[m_osxView maxValue];
1719 wxBitmap wxWidgetCocoaImpl::GetBitmap() const
1723 // TODO: how to create a wxBitmap from NSImage?
1725 if ( [m_osxView respondsToSelector:@selector(image:)] )
1726 bmp = [m_osxView image];
1732 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
1734 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
1736 [m_osxView setImage:bitmap.GetNSImage()];
1737 [m_osxView setNeedsDisplay:YES];
1741 void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
1743 if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
1745 NSCellImagePosition pos;
1765 wxFAIL_MSG( "invalid image position" );
1769 [m_osxView setImagePosition:pos];
1773 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
1775 // implementation in subclass
1778 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
1780 r->x = r->y = r->width = r->height = 0;
1782 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
1784 NSRect former = [m_osxView frame];
1785 [m_osxView sizeToFit];
1786 NSRect best = [m_osxView frame];
1787 [m_osxView setFrame:former];
1788 r->width = (int)best.size.width;
1789 r->height = (int)best.size.height;
1793 bool wxWidgetCocoaImpl::IsEnabled() const
1795 if ( [m_osxView respondsToSelector:@selector(isEnabled) ] )
1796 return [m_osxView isEnabled];
1800 void wxWidgetCocoaImpl::Enable( bool enable )
1802 if ( [m_osxView respondsToSelector:@selector(setEnabled:) ] )
1803 [m_osxView setEnabled:enable];
1806 void wxWidgetCocoaImpl::PulseGauge()
1810 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
1814 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
1816 NSControlSize size = NSRegularControlSize;
1820 case wxWINDOW_VARIANT_NORMAL :
1821 size = NSRegularControlSize;
1824 case wxWINDOW_VARIANT_SMALL :
1825 size = NSSmallControlSize;
1828 case wxWINDOW_VARIANT_MINI :
1829 size = NSMiniControlSize;
1832 case wxWINDOW_VARIANT_LARGE :
1833 size = NSRegularControlSize;
1837 wxFAIL_MSG(wxT("unexpected window variant"));
1840 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
1841 [m_osxView setControlSize:size];
1842 else if ([m_osxView respondsToSelector:@selector(cell)])
1844 id cell = [(id)m_osxView cell];
1845 if ([cell respondsToSelector:@selector(setControlSize:)])
1846 [cell setControlSize:size];
1850 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&, long, bool)
1852 if ([m_osxView respondsToSelector:@selector(setFont:)])
1853 [m_osxView setFont: font.OSXGetNSFont()];
1856 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
1858 WXWidget c = control ? control : (WXWidget) m_osxView;
1859 wxWidgetImpl::Associate( c, this ) ;
1860 if ([c respondsToSelector:@selector(setAction:)])
1863 [c setAction: @selector(controlAction:)];
1864 if ([c respondsToSelector:@selector(setDoubleAction:)])
1866 [c setDoubleAction: @selector(controlDoubleAction:)];
1872 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
1874 wxKeyEvent wxevent(wxEVT_CHAR);
1875 SetupKeyEvent( wxevent, event, text );
1877 return GetWXPeer()->OSXHandleKeyEvent(wxevent);
1880 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
1882 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1883 SetupKeyEvent( wxevent, event );
1884 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
1886 // this will fire higher level events, like insertText, to help
1887 // us handle EVT_CHAR, etc.
1889 if ( m_wxPeer->MacIsUserPane() && [event type] == NSKeyDown)
1893 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
1894 [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
1896 [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
1904 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
1906 NSPoint clickLocation;
1907 clickLocation = [m_osxView convertPoint:[event locationInWindow] fromView:nil];
1908 wxPoint pt = wxFromNSPoint( m_osxView, clickLocation );
1909 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
1910 SetupMouseEvent(wxevent , event) ;
1914 return GetWXPeer()->HandleWindowEvent(wxevent);
1917 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
1919 wxWindow* thisWindow = GetWXPeer();
1920 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
1922 thisWindow->MacInvalidateBorders();
1925 if ( receivedFocus )
1927 wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
1928 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
1929 thisWindow->HandleWindowEvent(eventFocus);
1932 if ( thisWindow->GetCaret() )
1933 thisWindow->GetCaret()->OnSetFocus();
1936 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
1937 event.SetEventObject(thisWindow);
1939 event.SetWindow(otherWindow->GetWXPeer());
1940 thisWindow->HandleWindowEvent(event) ;
1942 else // !receivedFocuss
1945 if ( thisWindow->GetCaret() )
1946 thisWindow->GetCaret()->OnKillFocus();
1949 wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
1951 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
1952 event.SetEventObject(thisWindow);
1954 event.SetWindow(otherWindow->GetWXPeer());
1955 thisWindow->HandleWindowEvent(event) ;
1959 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
1961 NSPoint location = [NSEvent mouseLocation];
1962 location = [[m_osxView window] convertScreenToBase:location];
1963 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
1965 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
1967 [(NSCursor*)cursor.GetHCURSOR() set];
1969 [[m_osxView window] invalidateCursorRectsForView:m_osxView];
1972 void wxWidgetCocoaImpl::CaptureMouse()
1974 [[m_osxView window] disableCursorRects];
1977 void wxWidgetCocoaImpl::ReleaseMouse()
1979 [[m_osxView window] enableCursorRects];
1982 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
1984 m_isFlipped = flipped;
1991 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
1992 wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
1993 long WXUNUSED(style), long WXUNUSED(extraStyle))
1995 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
1996 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
1998 // temporary hook for dnd
1999 [v registerForDraggedTypes:[NSArray arrayWithObjects:
2000 NSStringPboardType, NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSPDFPboardType, nil]];
2002 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v );
2006 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
2008 NSWindow* tlw = now->GetWXWindow();
2009 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2010 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( now, v, true );
2011 c->InstallEventHandler();
2012 [tlw setContentView:v];