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 = (wxevent.GetEventType() != wxEVT_CHAR) ? [nsEvent charactersIgnoringModifiers] : [nsEvent characters];
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 void wxWidgetCocoaImpl::SetupMouseEvent( wxMouseEvent &wxevent , NSEvent * nsEvent )
380 int eventType = [nsEvent type];
381 UInt32 modifiers = [nsEvent modifierFlags] ;
382 wxPoint screenMouseLocation = wxFromNSPoint( NULL, [nsEvent locationInWindow]);
384 // these parameters are not given for all events
385 UInt32 button = [nsEvent buttonNumber];
386 UInt32 clickCount = 0;
388 wxevent.m_x = screenMouseLocation.x;
389 wxevent.m_y = screenMouseLocation.y;
390 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
391 wxevent.m_controlDown = modifiers & NSControlKeyMask;
392 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
393 wxevent.m_metaDown = modifiers & NSCommandKeyMask;
394 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
396 UInt32 mouseChord = 0;
400 case NSLeftMouseDown :
401 case NSLeftMouseDragged :
404 case NSRightMouseDown :
405 case NSRightMouseDragged :
408 case NSOtherMouseDown :
409 case NSOtherMouseDragged :
414 // a control click is interpreted as a right click
415 bool thisButtonIsFakeRight = false ;
416 if ( button == 0 && (modifiers & NSControlKeyMask) )
419 thisButtonIsFakeRight = true ;
422 // otherwise we report double clicks by connecting a left click with a ctrl-left click
423 if ( clickCount > 1 && button != g_lastButton )
426 // we must make sure that our synthetic 'right' button corresponds in
427 // mouse down, moved and mouse up, and does not deliver a right down and left up
430 case NSLeftMouseDown :
431 case NSRightMouseDown :
432 case NSOtherMouseDown :
433 g_lastButton = button ;
434 g_lastButtonWasFakeRight = thisButtonIsFakeRight ;
441 g_lastButtonWasFakeRight = false ;
443 else if ( g_lastButton == 1 && g_lastButtonWasFakeRight )
444 button = g_lastButton ;
446 // Adjust the chord mask to remove the primary button and add the
447 // secondary button. It is possible that the secondary button is
448 // already pressed, e.g. on a mouse connected to a laptop, but this
449 // possibility is ignored here:
450 if( thisButtonIsFakeRight && ( mouseChord & 1U ) )
451 mouseChord = ((mouseChord & ~1U) | 2U);
454 wxevent.m_leftDown = true ;
456 wxevent.m_rightDown = true ;
458 wxevent.m_middleDown = true ;
460 // translate into wx types
463 case NSLeftMouseDown :
464 case NSRightMouseDown :
465 case NSOtherMouseDown :
466 clickCount = [nsEvent clickCount];
470 wxevent.SetEventType( clickCount > 1 ? wxEVT_LEFT_DCLICK : wxEVT_LEFT_DOWN ) ;
474 wxevent.SetEventType( clickCount > 1 ? wxEVT_RIGHT_DCLICK : wxEVT_RIGHT_DOWN ) ;
478 wxevent.SetEventType( clickCount > 1 ? wxEVT_MIDDLE_DCLICK : wxEVT_MIDDLE_DOWN ) ;
487 case NSRightMouseUp :
488 case NSOtherMouseUp :
489 clickCount = [nsEvent clickCount];
493 wxevent.SetEventType( wxEVT_LEFT_UP ) ;
497 wxevent.SetEventType( wxEVT_RIGHT_UP ) ;
501 wxevent.SetEventType( wxEVT_MIDDLE_UP ) ;
511 wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ;
512 wxevent.m_wheelDelta = 10;
513 wxevent.m_linesPerAction = 1;
515 if ( fabs([nsEvent deltaX]) > fabs([nsEvent deltaY]) )
517 wxevent.m_wheelAxis = 1;
518 wxevent.m_wheelRotation = (int)([nsEvent deltaX] * 10);
522 wxevent.m_wheelRotation = (int)([nsEvent deltaY] * 10);
527 case NSMouseEntered :
528 wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
531 wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
533 case NSLeftMouseDragged :
534 case NSRightMouseDragged :
535 case NSOtherMouseDragged :
537 wxevent.SetEventType( wxEVT_MOTION ) ;
543 wxevent.m_clickCount = clickCount;
544 wxWindowMac* peer = GetWXPeer();
547 wxevent.SetEventObject(peer);
548 wxevent.SetId(peer->GetId()) ;
552 @implementation wxNSView
556 static BOOL initialized = NO;
560 wxOSXCocoaClassAddWXMethods( self );
564 - (void) setTrackingTag: (NSTrackingRectTag)tag
569 - (NSTrackingRectTag) trackingTag
574 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
575 - (void) updateTrackingArea
579 [self removeTrackingArea: _trackingArea];
580 [_trackingArea release];
583 NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingMouseMoved|NSTrackingActiveAlways;
585 NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: [self bounds] options: options owner: self userInfo: nil];
586 [self addTrackingArea: area];
588 _trackingArea = area;
591 - (NSTrackingArea*) trackingArea
593 return _trackingArea;
602 #if wxUSE_DRAG_AND_DROP
604 // see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
605 // for details on the NSPasteboard -> PasteboardRef conversion
607 NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
609 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
611 return NSDragOperationNone;
613 return impl->draggingEntered(sender, self, _cmd);
616 void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
618 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
622 return impl->draggingExited(sender, self, _cmd);
625 NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
627 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
629 return NSDragOperationNone;
631 return impl->draggingUpdated(sender, self, _cmd);
634 BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
636 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
638 return NSDragOperationNone;
640 return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
645 void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
647 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
651 impl->mouseEvent(event, self, _cmd);
654 BOOL wxOSX_acceptsFirstMouse(NSView* self, SEL _cmd, NSEvent *event)
656 // This is needed to support click through, otherwise the first click on a window
657 // will not do anything unless it is the active window already.
661 void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
663 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
667 impl->keyEvent(event, self, _cmd);
670 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
672 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
676 impl->insertText(text, self, _cmd);
679 BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
681 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
685 return impl->performKeyEquivalent(event, self, _cmd);
688 BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
690 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
694 return impl->acceptsFirstResponder(self, _cmd);
697 BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
699 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
703 return impl->becomeFirstResponder(self, _cmd);
706 BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
708 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
712 return impl->resignFirstResponder(self, _cmd);
715 void wxOSX_resetCursorRects(NSView* self, SEL _cmd)
717 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
721 impl->resetCursorRects(self, _cmd);
724 BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
726 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
730 return impl->isFlipped(self, _cmd) ? YES:NO;
733 void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
735 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
739 return impl->drawRect(&rect, self, _cmd);
742 void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
744 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
748 impl->controlAction(self, _cmd, sender);
751 void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
753 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
757 impl->controlDoubleAction(self, _cmd, sender);
760 unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
762 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
763 NSPasteboard *pboard = [sender draggingPasteboard];
764 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
766 wxWindow* wxpeer = GetWXPeer();
767 if ( wxpeer == NULL )
768 return NSDragOperationNone;
770 wxDropTarget* target = wxpeer->GetDropTarget();
771 if ( target == NULL )
772 return NSDragOperationNone;
774 wxDragResult result = wxDragNone;
775 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
776 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
778 if ( sourceDragMask & NSDragOperationLink )
780 else if ( sourceDragMask & NSDragOperationCopy )
782 else if ( sourceDragMask & NSDragOperationMove )
785 PasteboardRef pboardRef;
786 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
787 target->SetCurrentDragPasteboard(pboardRef);
788 result = target->OnEnter(pt.x, pt.y, result);
789 CFRelease(pboardRef);
791 NSDragOperation nsresult = NSDragOperationNone;
795 nsresult = NSDragOperationLink;
797 nsresult = NSDragOperationMove;
799 nsresult = NSDragOperationCopy;
806 void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
808 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
809 NSPasteboard *pboard = [sender draggingPasteboard];
811 wxWindow* wxpeer = GetWXPeer();
812 if ( wxpeer == NULL )
815 wxDropTarget* target = wxpeer->GetDropTarget();
816 if ( target == NULL )
819 PasteboardRef pboardRef;
820 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
821 target->SetCurrentDragPasteboard(pboardRef);
823 CFRelease(pboardRef);
826 unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
828 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
829 NSPasteboard *pboard = [sender draggingPasteboard];
830 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
832 wxWindow* wxpeer = GetWXPeer();
833 if ( wxpeer == NULL )
834 return NSDragOperationNone;
836 wxDropTarget* target = wxpeer->GetDropTarget();
837 if ( target == NULL )
838 return NSDragOperationNone;
840 wxDragResult result = wxDragNone;
841 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
842 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
844 if ( sourceDragMask & NSDragOperationLink )
846 else if ( sourceDragMask & NSDragOperationCopy )
848 else if ( sourceDragMask & NSDragOperationMove )
851 PasteboardRef pboardRef;
852 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
853 target->SetCurrentDragPasteboard(pboardRef);
854 result = target->OnDragOver(pt.x, pt.y, result);
855 CFRelease(pboardRef);
857 NSDragOperation nsresult = NSDragOperationNone;
861 nsresult = NSDragOperationLink;
863 nsresult = NSDragOperationMove;
865 nsresult = NSDragOperationCopy;
872 bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
874 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
876 NSPasteboard *pboard = [sender draggingPasteboard];
877 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
879 wxWindow* wxpeer = GetWXPeer();
880 wxDropTarget* target = wxpeer->GetDropTarget();
881 wxDragResult result = wxDragNone;
882 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
883 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
885 if ( sourceDragMask & NSDragOperationLink )
887 else if ( sourceDragMask & NSDragOperationCopy )
889 else if ( sourceDragMask & NSDragOperationMove )
892 PasteboardRef pboardRef;
893 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
894 target->SetCurrentDragPasteboard(pboardRef);
896 if (target->OnDrop(pt.x, pt.y))
897 result = target->OnData(pt.x, pt.y, result);
899 CFRelease(pboardRef);
901 return result != wxDragNone;
904 typedef void (*wxOSX_TextEventHandlerPtr)(NSView* self, SEL _cmd, NSString *event);
905 typedef void (*wxOSX_EventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
906 typedef BOOL (*wxOSX_PerformKeyEventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
907 typedef BOOL (*wxOSX_FocusHandlerPtr)(NSView* self, SEL _cmd);
908 typedef BOOL (*wxOSX_ResetCursorRectsHandlerPtr)(NSView* self, SEL _cmd);
909 typedef void (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
911 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
913 if ( !DoHandleMouseEvent(event) )
915 // for plain NSView mouse events would propagate to parents otherwise
916 if (!m_wxPeer->MacIsUserPane())
918 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
919 superimpl(slf, (SEL)_cmd, event);
924 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
926 if ( [event type] == NSKeyDown )
927 m_lastKeyDownEvent = event;
928 if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
930 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
931 superimpl(slf, (SEL)_cmd, event);
933 m_lastKeyDownEvent = NULL;
936 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
938 if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
940 wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
941 superimpl(slf, (SEL)_cmd, text);
946 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
948 wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
949 return superimpl(slf, (SEL)_cmd, event);
952 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
954 if ( m_wxPeer->MacIsUserPane() )
955 return m_wxPeer->AcceptsFocus();
958 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
959 return superimpl(slf, (SEL)_cmd);
963 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
965 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
966 // get the current focus before running becomeFirstResponder
967 NSView* otherView = FindFocus();
969 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
970 BOOL r = superimpl(slf, (SEL)_cmd);
973 DoNotifyFocusEvent( true, otherWindow );
979 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
981 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
982 BOOL r = superimpl(slf, (SEL)_cmd);
983 // get the current focus after running resignFirstResponder
984 // note that this value isn't reliable, it might return the same view that
986 NSView* otherView = FindFocus();
987 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
988 // NSTextViews have an editor as true responder, therefore the might get the
989 // resign notification if their editor takes over, don't trigger any event then
990 if ( r && !m_hasEditor)
992 DoNotifyFocusEvent( false, otherWindow );
997 void wxWidgetCocoaImpl::resetCursorRects(WXWidget slf, void *_cmd)
999 wxWindow* wxpeer = GetWXPeer();
1002 NSCursor *cursor = (NSCursor*)wxpeer->GetCursor().GetHCURSOR();
1005 wxOSX_ResetCursorRectsHandlerPtr superimpl = (wxOSX_ResetCursorRectsHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1006 superimpl(slf, (SEL)_cmd);
1010 [slf addCursorRect: [slf bounds]
1016 bool wxWidgetCocoaImpl::isFlipped(WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1022 #define OSX_DEBUG_DRAWING 0
1024 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
1026 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1027 CGContextSaveGState( context );
1029 #if OSX_DEBUG_DRAWING
1030 CGContextBeginPath( context );
1031 CGContextMoveToPoint(context, 0, 0);
1032 NSRect bounds = [self bounds];
1033 CGContextAddLineToPoint(context, 10, 0);
1034 CGContextMoveToPoint(context, 0, 0);
1035 CGContextAddLineToPoint(context, 0, 10);
1036 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1037 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1038 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1039 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1040 CGContextClosePath( context );
1041 CGContextStrokePath(context);
1046 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1047 CGContextScaleCTM( context, 1, -1 );
1051 const NSRect *rects;
1054 [slf getRectsBeingDrawn:&rects count:&count];
1055 for ( int i = 0 ; i < count ; ++i )
1057 updateRgn.Union(wxFromNSRect(slf, rects[i]) );
1060 wxWindow* wxpeer = GetWXPeer();
1061 wxpeer->GetUpdateRegion() = updateRgn;
1062 wxpeer->MacSetCGContextRef( context );
1064 bool handled = wxpeer->MacDoRedraw( 0 );
1066 CGContextRestoreGState( context );
1068 CGContextSaveGState( context );
1072 SEL _cmd = @selector(drawRect:);
1073 wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1074 superimpl(slf, _cmd, *(NSRect*)rect);
1075 CGContextRestoreGState( context );
1076 CGContextSaveGState( context );
1078 wxpeer->MacPaintChildrenBorders();
1079 wxpeer->MacSetCGContextRef( NULL );
1080 CGContextRestoreGState( context );
1083 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1085 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1087 wxpeer->OSXHandleClicked(0);
1090 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1096 #if OBJC_API_VERSION >= 2
1098 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1099 class_addMethod(c, s, i, t );
1103 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1108 void wxOSXCocoaClassAddWXMethods(Class c)
1111 #if OBJC_API_VERSION < 2
1112 static objc_method wxmethods[] =
1116 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1117 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1118 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1120 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1121 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1122 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1124 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1126 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1127 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1128 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1130 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
1132 wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1133 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1134 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1136 wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1137 wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1138 wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1140 wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1142 wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
1144 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1145 wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1146 wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1147 wxOSX_CLASS_ADD_METHOD(c, @selector(resetCursorRects), (IMP) wxOSX_resetCursorRects, "v@:" )
1149 wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1150 wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1152 wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1153 wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1155 #if wxUSE_DRAG_AND_DROP
1156 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1157 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1158 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1159 wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1162 #if OBJC_API_VERSION < 2
1164 static int method_count = WXSIZEOF( wxmethods );
1165 static objc_method_list *wxmethodlist = NULL;
1166 if ( wxmethodlist == NULL )
1168 wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1169 memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1170 wxmethodlist->method_count = method_count;
1171 wxmethodlist->obsolete = 0;
1173 class_addMethods( c, wxmethodlist );
1178 // C++ implementation class
1181 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1183 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl ) :
1184 wxWidgetImpl( peer, isRootControl )
1189 // check if the user wants to create the control initially hidden
1190 if ( !peer->IsShown() )
1191 SetVisibility(false);
1193 // gc aware handling
1195 CFRetain(m_osxView);
1196 [m_osxView release];
1199 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1204 void wxWidgetCocoaImpl::Init()
1208 m_lastKeyDownEvent = NULL;
1209 m_hasEditor = false;
1212 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1214 RemoveAssociations( this );
1216 if ( !IsRootControl() )
1218 NSView *sv = [m_osxView superview];
1220 [m_osxView removeFromSuperview];
1222 // gc aware handling
1224 CFRelease(m_osxView);
1227 bool wxWidgetCocoaImpl::IsVisible() const
1229 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1232 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1234 [m_osxView setHidden:(visible ? NO:YES)];
1237 // ----------------------------------------------------------------------------
1238 // window animation stuff
1239 // ----------------------------------------------------------------------------
1241 // define a delegate used to refresh the window during animation
1242 @interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
1248 - (id)init:(wxWindow *)win;
1252 // NSAnimationDelegate methods
1253 - (void)animationDidEnd:(NSAnimation*)animation;
1254 - (void)animation:(NSAnimation*)animation
1255 didReachProgressMark:(NSAnimationProgress)progress;
1258 @implementation wxNSAnimationDelegate
1260 - (id)init:(wxWindow *)win
1275 - (void)animation:(NSAnimation*)animation
1276 didReachProgressMark:(NSAnimationProgress)progress
1278 wxUnusedVar(animation);
1279 wxUnusedVar(progress);
1281 m_win->SendSizeEvent();
1284 - (void)animationDidEnd:(NSAnimation*)animation
1293 wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1295 wxShowEffect effect,
1298 // create the dictionary describing the animation to perform on this view
1300 viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1301 NSMutableDictionary * const
1302 dict = [NSMutableDictionary dictionaryWithCapacity:4];
1303 [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1305 // determine the start and end rectangles assuming we're hiding the window
1306 const wxRect rectOrig = win->GetRect();
1314 if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1315 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1316 effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1317 else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1318 effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1319 effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1320 else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1321 effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1322 effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1323 else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1324 effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1325 effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1330 case wxSHOW_EFFECT_ROLL_TO_LEFT:
1331 case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1335 case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1336 case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1337 rectEnd.x = rectStart.GetRight();
1341 case wxSHOW_EFFECT_ROLL_TO_TOP:
1342 case wxSHOW_EFFECT_SLIDE_TO_TOP:
1346 case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1347 case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1348 rectEnd.y = rectStart.GetBottom();
1352 case wxSHOW_EFFECT_EXPAND:
1353 rectEnd.x = rectStart.x + rectStart.width / 2;
1354 rectEnd.y = rectStart.y + rectStart.height / 2;
1359 case wxSHOW_EFFECT_BLEND:
1360 [dict setObject:(show ? NSViewAnimationFadeInEffect
1361 : NSViewAnimationFadeOutEffect)
1362 forKey:NSViewAnimationEffectKey];
1365 case wxSHOW_EFFECT_NONE:
1366 case wxSHOW_EFFECT_MAX:
1367 wxFAIL_MSG( "unexpected animation effect" );
1371 wxFAIL_MSG( "unknown animation effect" );
1377 // we need to restore it to the original rectangle instead of making it
1379 wxSwap(rectStart, rectEnd);
1381 // and as the window is currently hidden, we need to show it for the
1382 // animation to be visible at all (but don't restore it at its full
1383 // rectangle as it shouldn't appear immediately)
1384 win->SetSize(rectStart);
1388 NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1389 ? [(NSView *)viewOrWin superview]
1391 const NSRect rStart = wxToNSRect(parentView, rectStart);
1392 const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1394 [dict setObject:[NSValue valueWithRect:rStart]
1395 forKey:NSViewAnimationStartFrameKey];
1396 [dict setObject:[NSValue valueWithRect:rEnd]
1397 forKey:NSViewAnimationEndFrameKey];
1399 // create an animation using the values in the above dictionary
1400 NSViewAnimation * const
1401 anim = [[NSViewAnimation alloc]
1402 initWithViewAnimations:[NSArray arrayWithObject:dict]];
1406 // what is a good default duration? Windows uses 200ms, Web frameworks
1407 // use anything from 250ms to 1s... choose something in the middle
1411 [anim setDuration:timeout/1000.]; // duration is in seconds here
1413 // if the window being animated changes its layout depending on its size
1414 // (which is almost always the case) we need to redo it during animation
1416 // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1417 // controls in wxInfoBar visibly jump around)
1418 const int NUM_LAYOUTS = 20;
1419 for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1420 [anim addProgressMark:f];
1422 wxNSAnimationDelegate * const
1423 animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1424 [anim setDelegate:animDelegate];
1425 [anim startAnimation];
1427 // Cocoa is capable of doing animation asynchronously or even from separate
1428 // thread but wx API doesn't provide any way to be notified about the
1429 // animation end and without this we really must ensure that the window has
1430 // the expected (i.e. the same as if a simple Show() had been used) size
1431 // when we return, so block here until the animation finishes
1433 // notice that because the default animation mode is NSAnimationBlocking,
1434 // no user input events ought to be processed from here
1436 wxEventLoopGuarantor ensureEventLoopExistence;
1437 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1438 while ( ![animDelegate isDone] )
1444 // NSViewAnimation is smart enough to hide the NSView being animated at
1445 // the end but we also must ensure that it's hidden for wx too
1448 // and we must also restore its size because it isn't expected to
1449 // change just because the window was hidden
1450 win->SetSize(rectOrig);
1454 // refresh it once again after the end to ensure that everything is in
1456 win->SendSizeEvent();
1459 [anim setDelegate:nil];
1460 [animDelegate release];
1466 bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
1467 wxShowEffect effect,
1470 return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
1473 void wxWidgetCocoaImpl::Raise()
1478 void wxWidgetCocoaImpl::Lower()
1483 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
1488 // We should do something like this, but it wasn't working in 10.4.
1489 if (GetNeedsDisplay() )
1493 NSRect r = wxToNSRect( [m_osxView superview], *rect );
1494 NSSize offset = NSMakeSize((float)dx, (float)dy);
1495 [m_osxView scrollRect:r by:offset];
1499 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
1501 wxWindowMac* parent = GetWXPeer()->GetParent();
1502 // under Cocoa we might have a contentView in the wxParent to which we have to
1503 // adjust the coordinates
1504 if (parent && [m_osxView superview] != parent->GetHandle() )
1506 int cx = 0,cy = 0,cw = 0,ch = 0;
1507 if ( parent->GetPeer() )
1509 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
1514 [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
1515 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
1516 [m_osxView setFrame:r];
1517 [[m_osxView superview] setNeedsDisplayInRect:r];
1519 wxNSView* wxview = (wxNSView*)m_osxView;
1520 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
1521 if ([wxview respondsToSelector:@selector(updateTrackingArea)] )
1522 [wxview updateTrackingArea];
1524 if ([m_osxView respondsToSelector:@selector(trackingTag)] )
1526 if ( [wxview trackingTag] )
1527 [wxview removeTrackingRect: [wxview trackingTag]];
1529 [wxview setTrackingTag: [wxview addTrackingRect: [m_osxView bounds] owner: wxview userData: nil assumeInside: NO]];
1534 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
1536 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
1541 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
1543 NSRect rect = [m_osxView frame];
1544 width = (int)rect.size.width;
1545 height = (int)rect.size.height;
1548 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
1550 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
1552 NSView* cv = [m_osxView contentView];
1554 NSRect bounds = [m_osxView bounds];
1555 NSRect rect = [cv frame];
1557 int y = (int)rect.origin.y;
1558 int x = (int)rect.origin.x;
1559 if ( ![ m_osxView isFlipped ] )
1560 y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
1563 width = (int)rect.size.width;
1564 height = (int)rect.size.height;
1569 GetSize( width, height );
1573 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
1576 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
1578 [m_osxView setNeedsDisplay:YES];
1581 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
1583 return [m_osxView needsDisplay];
1586 bool wxWidgetCocoaImpl::CanFocus() const
1588 return [m_osxView canBecomeKeyView] == YES;
1591 bool wxWidgetCocoaImpl::HasFocus() const
1593 return ( FindFocus() == m_osxView );
1596 bool wxWidgetCocoaImpl::SetFocus()
1598 if ( [m_osxView canBecomeKeyView] == NO )
1601 [[m_osxView window] makeFirstResponder: m_osxView] ;
1602 [[m_osxView window] makeKeyAndOrderFront:nil] ;
1607 void wxWidgetCocoaImpl::RemoveFromParent()
1609 [m_osxView removeFromSuperview];
1612 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
1614 NSView* container = parent->GetWXWidget() ;
1615 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
1616 [container addSubview:m_osxView];
1619 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
1621 NSView* targetView = m_osxView;
1622 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
1623 targetView = [(NSScrollView*) m_osxView documentView];
1625 if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
1627 [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
1628 green:(CGFloat) (col.Green() / 255.0)
1629 blue:(CGFloat) (col.Blue() / 255.0)
1630 alpha:(CGFloat) (col.Alpha() / 255.0)]];
1634 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
1636 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
1638 wxCFStringRef cf( title , encoding );
1639 [m_osxView setTitle:cf.AsNSString()];
1641 else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
1643 wxCFStringRef cf( title , encoding );
1644 [m_osxView setStringValue:cf.AsNSString()];
1649 void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
1651 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
1652 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
1653 *pt = wxFromNSPoint( to->GetWXWidget(), p );
1656 wxInt32 wxWidgetCocoaImpl::GetValue() const
1658 return [(NSControl*)m_osxView intValue];
1661 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
1663 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
1665 [m_osxView setIntValue:v];
1667 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
1669 [m_osxView setFloatValue:(double)v];
1671 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
1673 [m_osxView setDoubleValue:(double)v];
1677 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
1679 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
1681 [m_osxView setMinValue:(double)v];
1685 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
1687 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
1689 [m_osxView setMaxValue:(double)v];
1693 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
1695 if ( [m_osxView respondsToSelector:@selector(getMinValue:)] )
1697 return (int)[m_osxView minValue];
1702 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
1704 if ( [m_osxView respondsToSelector:@selector(getMaxValue:)] )
1706 return (int)[m_osxView maxValue];
1711 wxBitmap wxWidgetCocoaImpl::GetBitmap() const
1715 // TODO: how to create a wxBitmap from NSImage?
1717 if ( [m_osxView respondsToSelector:@selector(image:)] )
1718 bmp = [m_osxView image];
1724 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
1726 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
1728 [m_osxView setImage:bitmap.GetNSImage()];
1729 [m_osxView setNeedsDisplay:YES];
1733 void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
1735 if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
1737 NSCellImagePosition pos;
1757 wxFAIL_MSG( "invalid image position" );
1761 [m_osxView setImagePosition:pos];
1765 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
1767 // implementation in subclass
1770 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
1772 r->x = r->y = r->width = r->height = 0;
1774 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
1776 NSRect former = [m_osxView frame];
1777 [m_osxView sizeToFit];
1778 NSRect best = [m_osxView frame];
1779 [m_osxView setFrame:former];
1780 r->width = (int)best.size.width;
1781 r->height = (int)best.size.height;
1785 bool wxWidgetCocoaImpl::IsEnabled() const
1787 if ( [m_osxView respondsToSelector:@selector(isEnabled) ] )
1788 return [m_osxView isEnabled];
1792 void wxWidgetCocoaImpl::Enable( bool enable )
1794 if ( [m_osxView respondsToSelector:@selector(setEnabled:) ] )
1795 [m_osxView setEnabled:enable];
1798 void wxWidgetCocoaImpl::PulseGauge()
1802 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
1806 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
1808 NSControlSize size = NSRegularControlSize;
1812 case wxWINDOW_VARIANT_NORMAL :
1813 size = NSRegularControlSize;
1816 case wxWINDOW_VARIANT_SMALL :
1817 size = NSSmallControlSize;
1820 case wxWINDOW_VARIANT_MINI :
1821 size = NSMiniControlSize;
1824 case wxWINDOW_VARIANT_LARGE :
1825 size = NSRegularControlSize;
1829 wxFAIL_MSG(wxT("unexpected window variant"));
1832 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
1833 [m_osxView setControlSize:size];
1834 else if ([m_osxView respondsToSelector:@selector(cell)])
1836 id cell = [(id)m_osxView cell];
1837 if ([cell respondsToSelector:@selector(setControlSize:)])
1838 [cell setControlSize:size];
1842 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&, long, bool)
1844 if ([m_osxView respondsToSelector:@selector(setFont:)])
1845 [m_osxView setFont: font.OSXGetNSFont()];
1848 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
1850 WXWidget c = control ? control : (WXWidget) m_osxView;
1851 wxWidgetImpl::Associate( c, this ) ;
1852 if ([c respondsToSelector:@selector(setAction:)])
1855 [c setAction: @selector(controlAction:)];
1856 if ([c respondsToSelector:@selector(setDoubleAction:)])
1858 [c setDoubleAction: @selector(controlDoubleAction:)];
1864 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
1866 wxKeyEvent wxevent(wxEVT_CHAR);
1867 SetupKeyEvent( wxevent, event, text );
1869 return GetWXPeer()->OSXHandleKeyEvent(wxevent);
1872 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
1874 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1875 SetupKeyEvent( wxevent, event );
1876 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
1878 // this will fire higher level events, like insertText, to help
1879 // us handle EVT_CHAR, etc.
1881 if ( m_wxPeer->MacIsUserPane() && [event type] == NSKeyDown)
1885 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
1886 [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
1888 [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
1896 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
1898 NSPoint clickLocation;
1899 clickLocation = [m_osxView convertPoint:[event locationInWindow] fromView:nil];
1900 wxPoint pt = wxFromNSPoint( m_osxView, clickLocation );
1901 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
1902 SetupMouseEvent(wxevent , event) ;
1906 return GetWXPeer()->HandleWindowEvent(wxevent);
1909 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
1911 wxWindow* thisWindow = GetWXPeer();
1912 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
1914 thisWindow->MacInvalidateBorders();
1917 if ( receivedFocus )
1919 wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
1920 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
1921 thisWindow->HandleWindowEvent(eventFocus);
1924 if ( thisWindow->GetCaret() )
1925 thisWindow->GetCaret()->OnSetFocus();
1928 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
1929 event.SetEventObject(thisWindow);
1931 event.SetWindow(otherWindow->GetWXPeer());
1932 thisWindow->HandleWindowEvent(event) ;
1934 else // !receivedFocuss
1937 if ( thisWindow->GetCaret() )
1938 thisWindow->GetCaret()->OnKillFocus();
1941 wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
1943 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
1944 event.SetEventObject(thisWindow);
1946 event.SetWindow(otherWindow->GetWXPeer());
1947 thisWindow->HandleWindowEvent(event) ;
1951 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
1953 NSPoint location = [NSEvent mouseLocation];
1954 location = [[m_osxView window] convertScreenToBase:location];
1955 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
1957 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
1959 [(NSCursor*)cursor.GetHCURSOR() set];
1961 [[m_osxView window] invalidateCursorRectsForView:m_osxView];
1964 void wxWidgetCocoaImpl::CaptureMouse()
1966 [[m_osxView window] disableCursorRects];
1969 void wxWidgetCocoaImpl::ReleaseMouse()
1971 [[m_osxView window] enableCursorRects];
1974 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
1976 m_isFlipped = flipped;
1983 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
1984 wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
1985 long WXUNUSED(style), long WXUNUSED(extraStyle))
1987 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
1988 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
1990 // temporary hook for dnd
1991 [v registerForDraggedTypes:[NSArray arrayWithObjects:
1992 NSStringPboardType, NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSPDFPboardType, nil]];
1994 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v );
1998 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
2000 NSWindow* tlw = now->GetWXWindow();
2001 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2002 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( now, v, true );
2003 c->InstallEventHandler();
2004 [tlw setContentView:v];