1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/cocoa/window.mm
3 // Purpose: widgets (non tlw) for cocoa
4 // Author: Stefan Csomor
8 // Copyright: (c) Stefan Csomor
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 #include "wx/wxprec.h"
15 #include "wx/dcclient.h"
18 #include "wx/textctrl.h"
19 #include "wx/combobox.h"
23 #include "wx/osx/private.h"
26 #include "wx/evtloop.h"
32 #if wxUSE_DRAG_AND_DROP
37 #include "wx/tooltip.h"
40 #include <objc/objc-runtime.h>
42 // Get the window with the focus
44 NSView* GetViewFromResponder( NSResponder* responder )
47 if ( [responder isKindOfClass:[NSTextView class]] )
49 NSView* delegate = (NSView*) [(NSTextView*)responder delegate];
50 if ( [delegate isKindOfClass:[NSTextField class] ] )
53 view = (NSView*) responder;
57 if ( [responder isKindOfClass:[NSView class]] )
58 view = (NSView*) responder;
63 NSView* GetFocusedViewInWindow( NSWindow* keyWindow )
65 NSView* focusedView = nil;
66 if ( keyWindow != nil )
67 focusedView = GetViewFromResponder([keyWindow firstResponder]);
72 WXWidget wxWidgetImpl::FindFocus()
74 return GetFocusedViewInWindow( [NSApp keyWindow] );
77 NSRect wxOSXGetFrameForControl( wxWindowMac* window , const wxPoint& pos , const wxSize &size , bool adjustForOrigin )
81 window->MacGetBoundsForControl( pos , size , x , y, w, h , adjustForOrigin ) ;
82 wxRect bounds(x,y,w,h);
83 NSView* sv = (window->GetParent()->GetHandle() );
85 return wxToNSRect( sv, bounds );
88 @interface wxNSView : NSView
90 NSTrackingRectTag rectTag;
91 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
92 NSTrackingArea* _trackingArea;
96 // the tracking tag is needed to track mouse enter / exit events
97 - (void) setTrackingTag: (NSTrackingRectTag)tag;
98 - (NSTrackingRectTag) trackingTag;
99 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
100 // under 10.5 we can also track mouse moved events on non-focused windows if
101 // we use the new NSTrackingArea APIs.
102 - (void) updateTrackingArea;
103 - (NSTrackingArea*) trackingArea;
107 @interface NSView(PossibleMethods)
108 - (void)setTitle:(NSString *)aString;
109 - (void)setStringValue:(NSString *)aString;
110 - (void)setIntValue:(int)anInt;
111 - (void)setFloatValue:(float)aFloat;
112 - (void)setDoubleValue:(double)aDouble;
116 - (void)setMinValue:(double)aDouble;
117 - (void)setMaxValue:(double)aDouble;
122 - (void)setEnabled:(BOOL)flag;
124 - (void)setImage:(NSImage *)image;
125 - (void)setControlSize:(NSControlSize)size;
127 - (void)setFont:(NSFont *)fontObject;
131 - (void)setTarget:(id)anObject;
132 - (void)setAction:(SEL)aSelector;
133 - (void)setDoubleAction:(SEL)aSelector;
134 - (void)setBackgroundColor:(NSColor*)aColor;
135 - (void)setOpaque:(BOOL)opaque;
136 - (void)setTextColor:(NSColor *)color;
137 - (void)setImagePosition:(NSCellImagePosition)aPosition;
140 long wxOSXTranslateCocoaKey( NSEvent* event, int eventType )
144 if ([event type] != NSFlagsChanged)
146 NSString* s = [event charactersIgnoringModifiers];
147 // backspace char reports as delete w/modifiers for some reason
150 if ( eventType == wxEVT_CHAR && ([event modifierFlags] & NSControlKeyMask) && ( [s characterAtIndex:0] >= 'a' && [s characterAtIndex:0] <= 'z' ) )
152 retval = WXK_CONTROL_A + ([s characterAtIndex:0] - 'a');
156 switch ( [s characterAtIndex:0] )
163 case NSUpArrowFunctionKey :
166 case NSDownArrowFunctionKey :
169 case NSLeftArrowFunctionKey :
172 case NSRightArrowFunctionKey :
175 case NSInsertFunctionKey :
178 case NSDeleteFunctionKey :
181 case NSHomeFunctionKey :
184 // case NSBeginFunctionKey :
185 // retval = WXK_BEGIN;
187 case NSEndFunctionKey :
190 case NSPageUpFunctionKey :
193 case NSPageDownFunctionKey :
194 retval = WXK_PAGEDOWN;
196 case NSHelpFunctionKey :
200 int intchar = [s characterAtIndex: 0];
201 if ( intchar >= NSF1FunctionKey && intchar <= NSF24FunctionKey )
202 retval = WXK_F1 + (intchar - NSF1FunctionKey );
203 else if ( intchar > 0 && intchar < 32 )
211 // Some keys don't seem to have constants. The code mimics the approach
212 // taken by WebKit. See:
213 // http://trac.webkit.org/browser/trunk/WebCore/platform/mac/KeyEventMac.mm
214 switch( [event keyCode] )
219 retval = WXK_CONTROL;
223 retval = WXK_CAPITAL;
226 case 56: // Left Shift
227 case 60: // Right Shift
232 case 61: // Right Alt
236 case 59: // Left Ctrl
237 case 62: // Right Ctrl
238 retval = WXK_RAW_CONTROL;
250 retval = WXK_NUMPAD_DIVIDE;
253 retval = WXK_NUMPAD_MULTIPLY;
256 retval = WXK_NUMPAD_SUBTRACT;
259 retval = WXK_NUMPAD_ADD;
262 retval = WXK_NUMPAD_ENTER;
265 retval = WXK_NUMPAD_DECIMAL;
268 retval = WXK_NUMPAD0;
271 retval = WXK_NUMPAD1;
274 retval = WXK_NUMPAD2;
277 retval = WXK_NUMPAD3;
280 retval = WXK_NUMPAD4;
283 retval = WXK_NUMPAD5;
286 retval = WXK_NUMPAD6;
289 retval = WXK_NUMPAD7;
292 retval = WXK_NUMPAD8;
295 retval = WXK_NUMPAD9;
298 //retval = [event keyCode];
304 void wxWidgetCocoaImpl::SetupKeyEvent(wxKeyEvent &wxevent , NSEvent * nsEvent, NSString* charString)
306 UInt32 modifiers = [nsEvent modifierFlags] ;
307 int eventType = [nsEvent type];
309 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
310 wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
311 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
312 wxevent.m_controlDown = modifiers & NSCommandKeyMask;
314 wxevent.m_rawCode = [nsEvent keyCode];
315 wxevent.m_rawFlags = modifiers;
317 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
320 if ( eventType != NSFlagsChanged )
322 NSString* nschars = [[nsEvent charactersIgnoringModifiers] uppercaseString];
325 // if charString is set, it did not come from key up / key down
326 wxevent.SetEventType( wxEVT_CHAR );
327 chars = wxCFStringRef::AsString(charString);
331 chars = wxCFStringRef::AsString(nschars);
335 int aunichar = chars.Length() > 0 ? chars[0] : 0;
338 if (wxevent.GetEventType() != wxEVT_CHAR)
340 keyval = wxOSXTranslateCocoaKey(nsEvent, wxevent.GetEventType()) ;
344 wxevent.SetEventType( wxEVT_KEY_DOWN ) ;
347 wxevent.SetEventType( wxEVT_KEY_UP ) ;
349 case NSFlagsChanged :
353 wxevent.SetEventType( wxevent.m_controlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
356 wxevent.SetEventType( wxevent.m_shiftDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
359 wxevent.SetEventType( wxevent.m_altDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
361 case WXK_RAW_CONTROL:
362 wxevent.SetEventType( wxevent.m_rawControlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
373 if ( wxevent.GetEventType() == wxEVT_KEY_UP || wxevent.GetEventType() == wxEVT_KEY_DOWN )
374 keyval = wxToupper( aunichar ) ;
380 // OS X generates events with key codes in Unicode private use area for
381 // unprintable symbols such as cursor arrows (WXK_UP is mapped to U+F700)
382 // and function keys (WXK_F2 is U+F705). We don't want to use them as the
383 // result of wxKeyEvent::GetUnicodeKey() however as it's supposed to return
384 // WXK_NONE for "non characters" so explicitly exclude them.
386 // We only exclude the private use area inside the Basic Multilingual Plane
387 // as key codes beyond it don't seem to be currently used.
388 if ( !(aunichar >= 0xe000 && aunichar < 0xf900) )
389 wxevent.m_uniChar = aunichar;
391 wxevent.m_keyCode = keyval;
393 wxWindowMac* peer = GetWXPeer();
396 wxevent.SetEventObject(peer);
397 wxevent.SetId(peer->GetId()) ;
401 UInt32 g_lastButton = 0 ;
402 bool g_lastButtonWasFakeRight = false ;
404 // better scroll wheel support
405 // see http://lists.apple.com/archives/cocoa-dev/2007/Feb/msg00050.html
407 @interface NSEvent (DeviceDelta)
408 - (CGFloat)deviceDeltaX;
409 - (CGFloat)deviceDeltaY;
412 void wxWidgetCocoaImpl::SetupMouseEvent( wxMouseEvent &wxevent , NSEvent * nsEvent )
414 int eventType = [nsEvent type];
415 UInt32 modifiers = [nsEvent modifierFlags] ;
417 NSPoint locationInWindow = [nsEvent locationInWindow];
419 // adjust coordinates for the window of the target view
420 if ( [nsEvent window] != [m_osxView window] )
422 if ( [nsEvent window] != nil )
423 locationInWindow = [[nsEvent window] convertBaseToScreen:locationInWindow];
425 if ( [m_osxView window] != nil )
426 locationInWindow = [[m_osxView window] convertScreenToBase:locationInWindow];
429 NSPoint locationInView = [m_osxView convertPoint:locationInWindow fromView:nil];
430 wxPoint locationInViewWX = wxFromNSPoint( m_osxView, locationInView );
432 // these parameters are not given for all events
433 UInt32 button = [nsEvent buttonNumber];
434 UInt32 clickCount = 0;
436 wxevent.m_x = locationInViewWX.x;
437 wxevent.m_y = locationInViewWX.y;
438 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
439 wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
440 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
441 wxevent.m_controlDown = modifiers & NSCommandKeyMask;
442 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
444 UInt32 mouseChord = 0;
448 case NSLeftMouseDown :
449 case NSLeftMouseDragged :
452 case NSRightMouseDown :
453 case NSRightMouseDragged :
456 case NSOtherMouseDown :
457 case NSOtherMouseDragged :
462 // a control click is interpreted as a right click
463 bool thisButtonIsFakeRight = false ;
464 if ( button == 0 && (modifiers & NSControlKeyMask) )
467 thisButtonIsFakeRight = true ;
470 // otherwise we report double clicks by connecting a left click with a ctrl-left click
471 if ( clickCount > 1 && button != g_lastButton )
474 // we must make sure that our synthetic 'right' button corresponds in
475 // mouse down, moved and mouse up, and does not deliver a right down and left up
478 case NSLeftMouseDown :
479 case NSRightMouseDown :
480 case NSOtherMouseDown :
481 g_lastButton = button ;
482 g_lastButtonWasFakeRight = thisButtonIsFakeRight ;
489 g_lastButtonWasFakeRight = false ;
491 else if ( g_lastButton == 1 && g_lastButtonWasFakeRight )
492 button = g_lastButton ;
494 // Adjust the chord mask to remove the primary button and add the
495 // secondary button. It is possible that the secondary button is
496 // already pressed, e.g. on a mouse connected to a laptop, but this
497 // possibility is ignored here:
498 if( thisButtonIsFakeRight && ( mouseChord & 1U ) )
499 mouseChord = ((mouseChord & ~1U) | 2U);
502 wxevent.m_leftDown = true ;
504 wxevent.m_rightDown = true ;
506 wxevent.m_middleDown = true ;
508 // translate into wx types
511 case NSLeftMouseDown :
512 case NSRightMouseDown :
513 case NSOtherMouseDown :
514 clickCount = [nsEvent clickCount];
518 wxevent.SetEventType( clickCount > 1 ? wxEVT_LEFT_DCLICK : wxEVT_LEFT_DOWN ) ;
522 wxevent.SetEventType( clickCount > 1 ? wxEVT_RIGHT_DCLICK : wxEVT_RIGHT_DOWN ) ;
526 wxevent.SetEventType( clickCount > 1 ? wxEVT_MIDDLE_DCLICK : wxEVT_MIDDLE_DOWN ) ;
535 case NSRightMouseUp :
536 case NSOtherMouseUp :
537 clickCount = [nsEvent clickCount];
541 wxevent.SetEventType( wxEVT_LEFT_UP ) ;
545 wxevent.SetEventType( wxEVT_RIGHT_UP ) ;
549 wxevent.SetEventType( wxEVT_MIDDLE_UP ) ;
562 wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ;
564 // see http://developer.apple.com/qa/qa2005/qa1453.html
565 // for more details on why we have to look for the exact type
567 const EventRef cEvent = (EventRef) [nsEvent eventRef];
568 bool isMouseScrollEvent = false;
570 isMouseScrollEvent = ::GetEventKind(cEvent) == kEventMouseScroll;
572 if ( isMouseScrollEvent )
574 deltaX = [nsEvent deviceDeltaX];
575 deltaY = [nsEvent deviceDeltaY];
579 deltaX = ([nsEvent deltaX] * 10);
580 deltaY = ([nsEvent deltaY] * 10);
583 wxevent.m_wheelDelta = 10;
584 wxevent.m_linesPerAction = 1;
586 if ( fabs(deltaX) > fabs(deltaY) )
588 wxevent.m_wheelAxis = 1;
589 wxevent.m_wheelRotation = (int)deltaX;
593 wxevent.m_wheelRotation = (int)deltaY;
599 case NSMouseEntered :
600 wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
603 wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
605 case NSLeftMouseDragged :
606 case NSRightMouseDragged :
607 case NSOtherMouseDragged :
609 wxevent.SetEventType( wxEVT_MOTION ) ;
615 wxevent.m_clickCount = clickCount;
616 wxWindowMac* peer = GetWXPeer();
619 wxevent.SetEventObject(peer);
620 wxevent.SetId(peer->GetId()) ;
624 @implementation wxNSView
628 static BOOL initialized = NO;
632 wxOSXCocoaClassAddWXMethods( self );
636 - (void) setTrackingTag: (NSTrackingRectTag)tag
641 - (NSTrackingRectTag) trackingTag
646 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
647 - (void) updateTrackingArea
651 [self removeTrackingArea: _trackingArea];
652 [_trackingArea release];
655 NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingMouseMoved|NSTrackingActiveAlways;
657 NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: [self bounds] options: options owner: self userInfo: nil];
658 [self addTrackingArea: area];
660 _trackingArea = area;
663 - (NSTrackingArea*) trackingArea
665 return _trackingArea;
674 #if wxUSE_DRAG_AND_DROP
676 // see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
677 // for details on the NSPasteboard -> PasteboardRef conversion
679 NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
681 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
683 return NSDragOperationNone;
685 return impl->draggingEntered(sender, self, _cmd);
688 void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
690 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
694 return impl->draggingExited(sender, self, _cmd);
697 NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
699 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
701 return NSDragOperationNone;
703 return impl->draggingUpdated(sender, self, _cmd);
706 BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
708 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
710 return NSDragOperationNone;
712 return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
717 void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
719 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
723 impl->mouseEvent(event, self, _cmd);
726 BOOL wxOSX_acceptsFirstMouse(NSView* WXUNUSED(self), SEL WXUNUSED(_cmd), NSEvent *WXUNUSED(event))
728 // This is needed to support click through, otherwise the first click on a window
729 // will not do anything unless it is the active window already.
733 void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
735 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
739 impl->keyEvent(event, self, _cmd);
742 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
744 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
748 impl->insertText(text, self, _cmd);
751 BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
753 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
757 return impl->performKeyEquivalent(event, self, _cmd);
760 BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
762 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
766 return impl->acceptsFirstResponder(self, _cmd);
769 BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
771 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
775 return impl->becomeFirstResponder(self, _cmd);
778 BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
780 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
784 return impl->resignFirstResponder(self, _cmd);
787 void wxOSX_resetCursorRects(NSView* self, SEL _cmd)
789 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
793 impl->resetCursorRects(self, _cmd);
796 BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
798 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
802 return impl->isFlipped(self, _cmd) ? YES:NO;
805 typedef void (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
807 void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
809 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
814 // OS X starts a NSUIHeartBeatThread for animating the default button in a
815 // dialog. This causes a drawRect of the active dialog from outside the
816 // main UI thread. This causes an occasional crash since the wx drawing
817 // objects (like wxPen) are not thread safe.
819 // Notice that NSUIHeartBeatThread seems to be undocumented and doing
820 // [NSWindow setAllowsConcurrentViewDrawing:NO] does not affect it.
821 if ( !wxThread::IsMain() )
823 if ( impl->IsUserPane() )
825 wxWindow* win = impl->GetWXPeer();
826 if ( win->UseBgCol() )
829 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
830 CGContextSaveGState( context );
832 CGContextSetFillColorWithColor( context, win->GetBackgroundColour().GetCGColor());
833 CGRect r = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
834 CGContextFillRect( context, r );
836 CGContextRestoreGState( context );
841 // just call the superclass handler, we don't need any custom wx drawing
842 // here and it seems to work fine:
843 wxOSX_DrawRectHandlerPtr
844 superimpl = (wxOSX_DrawRectHandlerPtr)
845 [[self superclass] instanceMethodForSelector:_cmd];
846 superimpl(self, _cmd, rect);
851 #endif // wxUSE_THREADS
853 return impl->drawRect(&rect, self, _cmd);
856 void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
858 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
862 impl->controlAction(self, _cmd, sender);
865 void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
867 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
871 impl->controlDoubleAction(self, _cmd, sender);
874 unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
876 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
877 NSPasteboard *pboard = [sender draggingPasteboard];
878 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
880 wxWindow* wxpeer = GetWXPeer();
881 if ( wxpeer == NULL )
882 return NSDragOperationNone;
884 wxDropTarget* target = wxpeer->GetDropTarget();
885 if ( target == NULL )
886 return NSDragOperationNone;
888 wxDragResult result = wxDragNone;
889 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
890 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
892 if ( sourceDragMask & NSDragOperationLink )
894 else if ( sourceDragMask & NSDragOperationCopy )
896 else if ( sourceDragMask & NSDragOperationMove )
899 PasteboardRef pboardRef;
900 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
901 target->SetCurrentDragPasteboard(pboardRef);
902 result = target->OnEnter(pt.x, pt.y, result);
903 CFRelease(pboardRef);
905 NSDragOperation nsresult = NSDragOperationNone;
909 nsresult = NSDragOperationLink;
911 nsresult = NSDragOperationMove;
913 nsresult = NSDragOperationCopy;
920 void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
922 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
923 NSPasteboard *pboard = [sender draggingPasteboard];
925 wxWindow* wxpeer = GetWXPeer();
926 if ( wxpeer == NULL )
929 wxDropTarget* target = wxpeer->GetDropTarget();
930 if ( target == NULL )
933 PasteboardRef pboardRef;
934 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
935 target->SetCurrentDragPasteboard(pboardRef);
937 CFRelease(pboardRef);
940 unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
942 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
943 NSPasteboard *pboard = [sender draggingPasteboard];
944 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
946 wxWindow* wxpeer = GetWXPeer();
947 if ( wxpeer == NULL )
948 return NSDragOperationNone;
950 wxDropTarget* target = wxpeer->GetDropTarget();
951 if ( target == NULL )
952 return NSDragOperationNone;
954 wxDragResult result = wxDragNone;
955 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
956 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
958 if ( sourceDragMask & NSDragOperationLink )
960 else if ( sourceDragMask & NSDragOperationCopy )
962 else if ( sourceDragMask & NSDragOperationMove )
965 PasteboardRef pboardRef;
966 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
967 target->SetCurrentDragPasteboard(pboardRef);
968 result = target->OnDragOver(pt.x, pt.y, result);
969 CFRelease(pboardRef);
971 NSDragOperation nsresult = NSDragOperationNone;
975 nsresult = NSDragOperationLink;
977 nsresult = NSDragOperationMove;
979 nsresult = NSDragOperationCopy;
986 bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
988 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
990 NSPasteboard *pboard = [sender draggingPasteboard];
991 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
993 wxWindow* wxpeer = GetWXPeer();
994 wxDropTarget* target = wxpeer->GetDropTarget();
995 wxDragResult result = wxDragNone;
996 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
997 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
999 if ( sourceDragMask & NSDragOperationLink )
1000 result = wxDragLink;
1001 else if ( sourceDragMask & NSDragOperationCopy )
1002 result = wxDragCopy;
1003 else if ( sourceDragMask & NSDragOperationMove )
1004 result = wxDragMove;
1006 PasteboardRef pboardRef;
1007 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1008 target->SetCurrentDragPasteboard(pboardRef);
1010 if (target->OnDrop(pt.x, pt.y))
1011 result = target->OnData(pt.x, pt.y, result);
1013 CFRelease(pboardRef);
1015 return result != wxDragNone;
1018 typedef void (*wxOSX_TextEventHandlerPtr)(NSView* self, SEL _cmd, NSString *event);
1019 typedef void (*wxOSX_EventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
1020 typedef BOOL (*wxOSX_PerformKeyEventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
1021 typedef BOOL (*wxOSX_FocusHandlerPtr)(NSView* self, SEL _cmd);
1022 typedef BOOL (*wxOSX_ResetCursorRectsHandlerPtr)(NSView* self, SEL _cmd);
1024 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1026 if ( !DoHandleMouseEvent(event) )
1028 // for plain NSView mouse events would propagate to parents otherwise
1031 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1032 superimpl(slf, (SEL)_cmd, event);
1034 // super of built-ins keeps the mouse up, as wx expects this event, we have to synthesize it
1036 if ( [ event type] == NSLeftMouseDown )
1038 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
1039 SetupMouseEvent(wxevent , event) ;
1040 wxevent.SetEventType(wxEVT_LEFT_UP);
1042 GetWXPeer()->HandleWindowEvent(wxevent);
1048 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1050 if ( [event type] == NSKeyDown )
1052 // there are key equivalents that are not command-combos and therefore not handled by cocoa automatically,
1053 // therefore we call the menubar directly here, exit if the menu is handling the shortcut
1054 if ( [[[NSApplication sharedApplication] mainMenu] performKeyEquivalent:event] )
1057 m_lastKeyDownEvent = event;
1060 if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
1062 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1063 superimpl(slf, (SEL)_cmd, event);
1065 m_lastKeyDownEvent = NULL;
1068 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
1070 if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
1072 wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1073 superimpl(slf, (SEL)_cmd, text);
1078 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
1080 bool handled = false;
1082 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1083 SetupKeyEvent( wxevent, event );
1085 // because performKeyEquivalent is going up the entire view hierarchy, we don't have to
1086 // walk up the ancestors ourselves but let cocoa do it
1088 int command = m_wxPeer->GetAcceleratorTable()->GetCommand( wxevent );
1091 wxEvtHandler * const handler = m_wxPeer->GetEventHandler();
1093 wxCommandEvent command_event( wxEVT_COMMAND_MENU_SELECTED, command );
1094 command_event.SetEventObject( wxevent.GetEventObject() );
1095 handled = handler->ProcessEvent( command_event );
1099 // accelerators can also be used with buttons, try them too
1100 command_event.SetEventType(wxEVT_COMMAND_BUTTON_CLICKED);
1101 handled = handler->ProcessEvent( command_event );
1107 wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1108 return superimpl(slf, (SEL)_cmd, event);
1113 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
1116 return m_wxPeer->AcceptsFocus();
1119 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1120 return superimpl(slf, (SEL)_cmd);
1124 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
1126 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1127 // get the current focus before running becomeFirstResponder
1128 NSView* otherView = FindFocus();
1130 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1131 BOOL r = superimpl(slf, (SEL)_cmd);
1134 DoNotifyFocusEvent( true, otherWindow );
1140 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
1142 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1143 BOOL r = superimpl(slf, (SEL)_cmd);
1144 // get the current focus after running resignFirstResponder
1145 // note that this value isn't reliable, it might return the same view that
1147 NSView* otherView = FindFocus();
1148 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1150 // It doesn't make sense to notify about the loss of focus if we're not
1151 // really losing it and the window which has just gained focus is the same
1152 // one as this window itself. Of course, this should never happen in the
1153 // first place but somehow it does in wxGrid code and without this check we
1154 // enter into an infinite recursion, see #12267.
1155 if ( otherWindow == this )
1158 // NSTextViews have an editor as true responder, therefore the might get the
1159 // resign notification if their editor takes over, don't trigger any event then
1160 if ( r && !m_hasEditor)
1162 DoNotifyFocusEvent( false, otherWindow );
1167 void wxWidgetCocoaImpl::resetCursorRects(WXWidget slf, void *_cmd)
1169 wxWindow* wxpeer = GetWXPeer();
1172 NSCursor *cursor = (NSCursor*)wxpeer->GetCursor().GetHCURSOR();
1175 wxOSX_ResetCursorRectsHandlerPtr superimpl = (wxOSX_ResetCursorRectsHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1176 superimpl(slf, (SEL)_cmd);
1180 [slf addCursorRect: [slf bounds]
1186 bool wxWidgetCocoaImpl::isFlipped(WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1192 #define OSX_DEBUG_DRAWING 0
1194 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
1196 // preparing the update region
1199 const NSRect *rects;
1202 [slf getRectsBeingDrawn:&rects count:&count];
1203 for ( int i = 0 ; i < count ; ++i )
1205 updateRgn.Union(wxFromNSRect(slf, rects[i]));
1208 wxWindow* wxpeer = GetWXPeer();
1210 if ( wxpeer->MacGetLeftBorderSize() != 0 || wxpeer->MacGetTopBorderSize() != 0 )
1212 // as this update region is in native window locals we must adapt it to wx window local
1213 updateRgn.Offset( wxpeer->MacGetLeftBorderSize() , wxpeer->MacGetTopBorderSize() );
1216 // Restrict the update region to the shape of the window, if any, and also
1217 // remember the region that we need to clear later.
1218 wxNonOwnedWindow* const tlwParent = wxpeer->MacGetTopLevelWindow();
1219 const bool isTopLevel = tlwParent == wxpeer;
1221 if ( tlwParent->GetWindowStyle() & wxFRAME_SHAPED )
1224 clearRgn = updateRgn;
1226 int xoffset = 0, yoffset = 0;
1227 wxRegion rgn = tlwParent->GetShape();
1228 wxpeer->MacRootWindowToWindow( &xoffset, &yoffset );
1229 rgn.Offset( xoffset, yoffset );
1230 updateRgn.Intersect(rgn);
1234 // Exclude the window shape from the region to be cleared below.
1235 rgn.Xor(wxpeer->GetSize());
1236 clearRgn.Intersect(rgn);
1240 wxpeer->GetUpdateRegion() = updateRgn;
1242 // setting up the drawing context
1244 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1245 CGContextSaveGState( context );
1247 #if OSX_DEBUG_DRAWING
1248 CGContextBeginPath( context );
1249 CGContextMoveToPoint(context, 0, 0);
1250 NSRect bounds = [slf bounds];
1251 CGContextAddLineToPoint(context, 10, 0);
1252 CGContextMoveToPoint(context, 0, 0);
1253 CGContextAddLineToPoint(context, 0, 10);
1254 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1255 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1256 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1257 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1258 CGContextClosePath( context );
1259 CGContextStrokePath(context);
1264 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1265 CGContextScaleCTM( context, 1, -1 );
1268 wxpeer->MacSetCGContextRef( context );
1270 bool handled = wxpeer->MacDoRedraw( 0 );
1271 CGContextRestoreGState( context );
1273 CGContextSaveGState( context );
1277 SEL _cmd = @selector(drawRect:);
1278 wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1279 superimpl(slf, _cmd, *(NSRect*)rect);
1280 CGContextRestoreGState( context );
1281 CGContextSaveGState( context );
1283 // as we called restore above, we have to flip again if necessary
1286 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1287 CGContextScaleCTM( context, 1, -1 );
1292 // We also need to explicitly draw the part of the top level window
1293 // outside of its region with transparent colour to ensure that it is
1294 // really transparent.
1295 if ( clearRgn.IsOk() )
1297 wxMacCGContextStateSaver saveState(context);
1298 wxWindowDC dc(wxpeer);
1299 dc.SetBackground(wxBrush(wxTransparentColour));
1300 dc.SetDeviceClippingRegion(clearRgn);
1304 #if wxUSE_GRAPHICS_CONTEXT
1305 // If the window shape is defined by a path, stroke the path to show
1306 // the window border.
1307 const wxGraphicsPath& path = tlwParent->GetShapePath();
1308 if ( !path.IsNull() )
1310 CGContextSetLineWidth(context, 1);
1311 CGContextSetStrokeColorWithColor(context, wxLIGHT_GREY->GetCGColor());
1312 CGContextAddPath(context, (CGPathRef) path.GetNativePath());
1313 CGContextStrokePath(context);
1315 #endif // wxUSE_GRAPHICS_CONTEXT
1318 wxpeer->MacPaintChildrenBorders();
1319 wxpeer->MacSetCGContextRef( NULL );
1320 CGContextRestoreGState( context );
1323 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1325 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1327 wxpeer->OSXHandleClicked(0);
1330 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1334 void wxWidgetCocoaImpl::controlTextDidChange()
1336 wxWindow* wxpeer = (wxWindow*)GetWXPeer();
1339 // since native rtti doesn't have to be enabled and wx' rtti is not aware of the mixin wxTextEntry, workaround is needed
1340 wxTextCtrl *tc = wxDynamicCast( wxpeer , wxTextCtrl );
1341 wxComboBox *cb = wxDynamicCast( wxpeer , wxComboBox );
1343 tc->SendTextUpdatedEventIfAllowed();
1345 cb->SendTextUpdatedEventIfAllowed();
1348 wxFAIL_MSG("Unexpected class for controlTextDidChange event");
1355 #if OBJC_API_VERSION >= 2
1357 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1358 class_addMethod(c, s, i, t );
1362 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1363 { s, (char*) t, i },
1367 void wxOSXCocoaClassAddWXMethods(Class c)
1370 #if OBJC_API_VERSION < 2
1371 static objc_method wxmethods[] =
1375 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1376 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1377 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1379 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1380 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1381 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1383 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1385 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1386 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1387 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1389 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
1391 wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1392 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1393 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1395 wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1396 wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1397 wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1399 wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1401 wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
1403 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1404 wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1405 wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1406 wxOSX_CLASS_ADD_METHOD(c, @selector(resetCursorRects), (IMP) wxOSX_resetCursorRects, "v@:" )
1408 wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1409 wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1411 wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1412 wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1414 #if wxUSE_DRAG_AND_DROP
1415 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1416 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1417 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1418 wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1421 #if OBJC_API_VERSION < 2
1423 static int method_count = WXSIZEOF( wxmethods );
1424 static objc_method_list *wxmethodlist = NULL;
1425 if ( wxmethodlist == NULL )
1427 wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1428 memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1429 wxmethodlist->method_count = method_count;
1430 wxmethodlist->obsolete = 0;
1432 class_addMethods( c, wxmethodlist );
1437 // C++ implementation class
1440 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1442 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl, bool isUserPane ) :
1443 wxWidgetImpl( peer, isRootControl, isUserPane )
1448 // check if the user wants to create the control initially hidden
1449 if ( !peer->IsShown() )
1450 SetVisibility(false);
1452 // gc aware handling
1454 CFRetain(m_osxView);
1455 [m_osxView release];
1458 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1463 void wxWidgetCocoaImpl::Init()
1467 m_lastKeyDownEvent = NULL;
1468 m_hasEditor = false;
1471 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1473 RemoveAssociations( this );
1475 if ( !IsRootControl() )
1477 NSView *sv = [m_osxView superview];
1479 [m_osxView removeFromSuperview];
1481 // gc aware handling
1483 CFRelease(m_osxView);
1486 bool wxWidgetCocoaImpl::IsVisible() const
1488 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1491 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1493 [m_osxView setHidden:(visible ? NO:YES)];
1496 // ----------------------------------------------------------------------------
1497 // window animation stuff
1498 // ----------------------------------------------------------------------------
1500 // define a delegate used to refresh the window during animation
1501 @interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
1507 - (id)init:(wxWindow *)win;
1511 // NSAnimationDelegate methods
1512 - (void)animationDidEnd:(NSAnimation*)animation;
1513 - (void)animation:(NSAnimation*)animation
1514 didReachProgressMark:(NSAnimationProgress)progress;
1517 @implementation wxNSAnimationDelegate
1519 - (id)init:(wxWindow *)win
1521 self = [super init];
1534 - (void)animation:(NSAnimation*)animation
1535 didReachProgressMark:(NSAnimationProgress)progress
1537 wxUnusedVar(animation);
1538 wxUnusedVar(progress);
1540 m_win->SendSizeEvent();
1543 - (void)animationDidEnd:(NSAnimation*)animation
1545 wxUnusedVar(animation);
1553 wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1555 wxShowEffect effect,
1558 // create the dictionary describing the animation to perform on this view
1560 viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1561 NSMutableDictionary * const
1562 dict = [NSMutableDictionary dictionaryWithCapacity:4];
1563 [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1565 // determine the start and end rectangles assuming we're hiding the window
1566 const wxRect rectOrig = win->GetRect();
1574 if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1575 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1576 effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1577 else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1578 effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1579 effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1580 else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1581 effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1582 effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1583 else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1584 effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1585 effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1590 case wxSHOW_EFFECT_ROLL_TO_LEFT:
1591 case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1595 case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1596 case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1597 rectEnd.x = rectStart.GetRight();
1601 case wxSHOW_EFFECT_ROLL_TO_TOP:
1602 case wxSHOW_EFFECT_SLIDE_TO_TOP:
1606 case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1607 case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1608 rectEnd.y = rectStart.GetBottom();
1612 case wxSHOW_EFFECT_EXPAND:
1613 rectEnd.x = rectStart.x + rectStart.width / 2;
1614 rectEnd.y = rectStart.y + rectStart.height / 2;
1619 case wxSHOW_EFFECT_BLEND:
1620 [dict setObject:(show ? NSViewAnimationFadeInEffect
1621 : NSViewAnimationFadeOutEffect)
1622 forKey:NSViewAnimationEffectKey];
1625 case wxSHOW_EFFECT_NONE:
1626 case wxSHOW_EFFECT_MAX:
1627 wxFAIL_MSG( "unexpected animation effect" );
1631 wxFAIL_MSG( "unknown animation effect" );
1637 // we need to restore it to the original rectangle instead of making it
1639 wxSwap(rectStart, rectEnd);
1641 // and as the window is currently hidden, we need to show it for the
1642 // animation to be visible at all (but don't restore it at its full
1643 // rectangle as it shouldn't appear immediately)
1644 win->SetSize(rectStart);
1648 NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1649 ? [(NSView *)viewOrWin superview]
1651 const NSRect rStart = wxToNSRect(parentView, rectStart);
1652 const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1654 [dict setObject:[NSValue valueWithRect:rStart]
1655 forKey:NSViewAnimationStartFrameKey];
1656 [dict setObject:[NSValue valueWithRect:rEnd]
1657 forKey:NSViewAnimationEndFrameKey];
1659 // create an animation using the values in the above dictionary
1660 NSViewAnimation * const
1661 anim = [[NSViewAnimation alloc]
1662 initWithViewAnimations:[NSArray arrayWithObject:dict]];
1666 // what is a good default duration? Windows uses 200ms, Web frameworks
1667 // use anything from 250ms to 1s... choose something in the middle
1671 [anim setDuration:timeout/1000.]; // duration is in seconds here
1673 // if the window being animated changes its layout depending on its size
1674 // (which is almost always the case) we need to redo it during animation
1676 // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1677 // controls in wxInfoBar visibly jump around)
1678 const int NUM_LAYOUTS = 20;
1679 for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1680 [anim addProgressMark:f];
1682 wxNSAnimationDelegate * const
1683 animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1684 [anim setDelegate:animDelegate];
1685 [anim startAnimation];
1687 // Cocoa is capable of doing animation asynchronously or even from separate
1688 // thread but wx API doesn't provide any way to be notified about the
1689 // animation end and without this we really must ensure that the window has
1690 // the expected (i.e. the same as if a simple Show() had been used) size
1691 // when we return, so block here until the animation finishes
1693 // notice that because the default animation mode is NSAnimationBlocking,
1694 // no user input events ought to be processed from here
1696 wxEventLoopGuarantor ensureEventLoopExistence;
1697 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1698 while ( ![animDelegate isDone] )
1704 // NSViewAnimation is smart enough to hide the NSView being animated at
1705 // the end but we also must ensure that it's hidden for wx too
1708 // and we must also restore its size because it isn't expected to
1709 // change just because the window was hidden
1710 win->SetSize(rectOrig);
1714 // refresh it once again after the end to ensure that everything is in
1716 win->SendSizeEvent();
1719 [anim setDelegate:nil];
1720 [animDelegate release];
1726 bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
1727 wxShowEffect effect,
1730 return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
1733 /* note that the drawing order between siblings is not defined under 10.4 */
1734 /* only starting from 10.5 the subview order is respected */
1736 /* NSComparisonResult is typedef'd as an enum pre-Leopard but typedef'd as
1737 * NSInteger post-Leopard. Pre-Leopard the Cocoa toolkit expects a function
1738 * returning int and not NSComparisonResult. Post-Leopard the Cocoa toolkit
1739 * expects a function returning the new non-enum NSComparsionResult.
1740 * Hence we create a typedef named CocoaWindowCompareFunctionResult.
1742 #if defined(NSINTEGER_DEFINED)
1743 typedef NSComparisonResult CocoaWindowCompareFunctionResult;
1745 typedef int CocoaWindowCompareFunctionResult;
1748 class CocoaWindowCompareContext
1750 wxDECLARE_NO_COPY_CLASS(CocoaWindowCompareContext);
1752 CocoaWindowCompareContext(); // Not implemented
1753 CocoaWindowCompareContext(NSView *target, NSArray *subviews)
1756 // Cocoa sorts subviews in-place.. make a copy
1757 m_subviews = [subviews copy];
1760 ~CocoaWindowCompareContext()
1761 { // release the copy
1762 [m_subviews release];
1765 { return m_target; }
1768 { return m_subviews; }
1770 /* Helper function that returns the comparison based off of the original ordering */
1771 CocoaWindowCompareFunctionResult CompareUsingOriginalOrdering(id first, id second)
1773 NSUInteger firstI = [m_subviews indexOfObjectIdenticalTo:first];
1774 NSUInteger secondI = [m_subviews indexOfObjectIdenticalTo:second];
1775 // NOTE: If either firstI or secondI is NSNotFound then it will be NSIntegerMax and thus will
1776 // likely compare higher than the other view which is reasonable considering the only way that
1777 // can happen is if the subview was added after our call to subviews but before the call to
1778 // sortSubviewsUsingFunction:context:. Thus we don't bother checking. Particularly because
1779 // that case should never occur anyway because that would imply a multi-threaded GUI call
1780 // which is a big no-no with Cocoa.
1782 // Subviews are ordered from back to front meaning one that is already lower will have an lower index.
1783 NSComparisonResult result = (firstI < secondI)
1784 ? NSOrderedAscending /* -1 */
1785 : (firstI > secondI)
1786 ? NSOrderedDescending /* 1 */
1787 : NSOrderedSame /* 0 */;
1792 /* The subview we are trying to Raise or Lower */
1794 /* A copy of the original array of subviews */
1795 NSArray *m_subviews;
1798 /* Causes Cocoa to raise the target view to the top of the Z-Order by telling the sort function that
1799 * the target view is always higher than every other view. When comparing two views neither of
1800 * which is the target, it returns the correct response based on the original ordering
1802 static CocoaWindowCompareFunctionResult CocoaRaiseWindowCompareFunction(id first, id second, void *ctx)
1804 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
1805 // first should be ordered higher
1806 if(first==compareContext->target())
1807 return NSOrderedDescending;
1808 // second should be ordered higher
1809 if(second==compareContext->target())
1810 return NSOrderedAscending;
1811 return compareContext->CompareUsingOriginalOrdering(first,second);
1814 void wxWidgetCocoaImpl::Raise()
1816 NSView* nsview = m_osxView;
1818 NSView *superview = [nsview superview];
1819 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
1821 [superview sortSubviewsUsingFunction:
1822 CocoaRaiseWindowCompareFunction
1823 context: &compareContext];
1827 /* Causes Cocoa to lower the target view to the bottom of the Z-Order by telling the sort function that
1828 * the target view is always lower than every other view. When comparing two views neither of
1829 * which is the target, it returns the correct response based on the original ordering
1831 static CocoaWindowCompareFunctionResult CocoaLowerWindowCompareFunction(id first, id second, void *ctx)
1833 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
1834 // first should be ordered lower
1835 if(first==compareContext->target())
1836 return NSOrderedAscending;
1837 // second should be ordered lower
1838 if(second==compareContext->target())
1839 return NSOrderedDescending;
1840 return compareContext->CompareUsingOriginalOrdering(first,second);
1843 void wxWidgetCocoaImpl::Lower()
1845 NSView* nsview = m_osxView;
1847 NSView *superview = [nsview superview];
1848 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
1850 [superview sortSubviewsUsingFunction:
1851 CocoaLowerWindowCompareFunction
1852 context: &compareContext];
1855 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
1860 // We should do something like this, but it wasn't working in 10.4.
1861 if (GetNeedsDisplay() )
1865 NSRect r = wxToNSRect( [m_osxView superview], *rect );
1866 NSSize offset = NSMakeSize((float)dx, (float)dy);
1867 [m_osxView scrollRect:r by:offset];
1871 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
1873 wxWindowMac* parent = GetWXPeer()->GetParent();
1874 // under Cocoa we might have a contentView in the wxParent to which we have to
1875 // adjust the coordinates
1876 if (parent && [m_osxView superview] != parent->GetHandle() )
1878 int cx = 0,cy = 0,cw = 0,ch = 0;
1879 if ( parent->GetPeer() )
1881 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
1886 [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
1887 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
1888 [m_osxView setFrame:r];
1889 [[m_osxView superview] setNeedsDisplayInRect:r];
1891 wxNSView* wxview = (wxNSView*)m_osxView;
1892 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
1893 if ([wxview respondsToSelector:@selector(updateTrackingArea)] )
1894 [wxview updateTrackingArea];
1896 if ([m_osxView respondsToSelector:@selector(trackingTag)] )
1898 if ( [wxview trackingTag] )
1899 [wxview removeTrackingRect: [wxview trackingTag]];
1901 [wxview setTrackingTag: [wxview addTrackingRect: [m_osxView bounds] owner: wxview userData: nil assumeInside: NO]];
1906 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
1908 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
1912 // under Cocoa we might have a contentView in the wxParent to which we have to
1913 // adjust the coordinates
1914 wxWindowMac* parent = GetWXPeer()->GetParent();
1915 if (parent && [m_osxView superview] != parent->GetHandle() )
1917 int cx = 0,cy = 0,cw = 0,ch = 0;
1918 if ( parent->GetPeer() )
1920 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
1927 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
1929 NSRect rect = [m_osxView frame];
1930 width = (int)rect.size.width;
1931 height = (int)rect.size.height;
1934 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
1936 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
1938 NSView* cv = [m_osxView contentView];
1940 NSRect bounds = [m_osxView bounds];
1941 NSRect rect = [cv frame];
1943 int y = (int)rect.origin.y;
1944 int x = (int)rect.origin.x;
1945 if ( ![ m_osxView isFlipped ] )
1946 y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
1949 width = (int)rect.size.width;
1950 height = (int)rect.size.height;
1955 GetSize( width, height );
1959 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
1962 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
1964 [m_osxView setNeedsDisplay:YES];
1967 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
1969 return [m_osxView needsDisplay];
1972 bool wxWidgetCocoaImpl::CanFocus() const
1974 return [m_osxView canBecomeKeyView] == YES;
1977 bool wxWidgetCocoaImpl::HasFocus() const
1979 return ( FindFocus() == m_osxView );
1982 bool wxWidgetCocoaImpl::SetFocus()
1987 // TODO remove if no issues arise: should not raise the window, only assign focus
1988 //[[m_osxView window] makeKeyAndOrderFront:nil] ;
1989 [[m_osxView window] makeFirstResponder: m_osxView] ;
1994 void wxWidgetCocoaImpl::RemoveFromParent()
1996 [m_osxView removeFromSuperview];
1999 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
2001 NSView* container = parent->GetWXWidget() ;
2002 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
2003 [container addSubview:m_osxView];
2006 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
2008 NSView* targetView = m_osxView;
2009 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2010 targetView = [(NSScrollView*) m_osxView documentView];
2012 if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
2014 [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2015 green:(CGFloat) (col.Green() / 255.0)
2016 blue:(CGFloat) (col.Blue() / 255.0)
2017 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2021 bool wxWidgetCocoaImpl::SetBackgroundStyle( wxBackgroundStyle style )
2023 BOOL opaque = ( style == wxBG_STYLE_PAINT );
2025 if ( [m_osxView respondsToSelector:@selector(setOpaque:) ] )
2027 [m_osxView setOpaque: opaque];
2033 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
2035 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
2037 wxCFStringRef cf( title , encoding );
2038 [m_osxView setTitle:cf.AsNSString()];
2040 else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
2042 wxCFStringRef cf( title , encoding );
2043 [m_osxView setStringValue:cf.AsNSString()];
2048 void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
2050 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
2051 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
2052 *pt = wxFromNSPoint( to->GetWXWidget(), p );
2055 wxInt32 wxWidgetCocoaImpl::GetValue() const
2057 return [(NSControl*)m_osxView intValue];
2060 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
2062 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
2064 [m_osxView setIntValue:v];
2066 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
2068 [m_osxView setFloatValue:(double)v];
2070 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
2072 [m_osxView setDoubleValue:(double)v];
2076 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
2078 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
2080 [m_osxView setMinValue:(double)v];
2084 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
2086 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
2088 [m_osxView setMaxValue:(double)v];
2092 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
2094 if ( [m_osxView respondsToSelector:@selector(minValue)] )
2096 return (int)[m_osxView minValue];
2101 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
2103 if ( [m_osxView respondsToSelector:@selector(maxValue)] )
2105 return (int)[m_osxView maxValue];
2110 wxBitmap wxWidgetCocoaImpl::GetBitmap() const
2114 // TODO: how to create a wxBitmap from NSImage?
2116 if ( [m_osxView respondsToSelector:@selector(image:)] )
2117 bmp = [m_osxView image];
2123 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
2125 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
2128 [m_osxView setImage:bitmap.GetNSImage()];
2130 [m_osxView setImage:nil];
2132 [m_osxView setNeedsDisplay:YES];
2136 void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
2138 if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
2140 NSCellImagePosition pos;
2160 wxFAIL_MSG( "invalid image position" );
2164 [m_osxView setImagePosition:pos];
2168 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
2170 // implementation in subclass
2173 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
2175 r->x = r->y = r->width = r->height = 0;
2177 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
2179 NSRect former = [m_osxView frame];
2180 [m_osxView sizeToFit];
2181 NSRect best = [m_osxView frame];
2182 [m_osxView setFrame:former];
2183 r->width = (int)best.size.width;
2184 r->height = (int)best.size.height;
2188 bool wxWidgetCocoaImpl::IsEnabled() const
2190 NSView* targetView = m_osxView;
2191 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2192 targetView = [(NSScrollView*) m_osxView documentView];
2194 if ( [targetView respondsToSelector:@selector(isEnabled) ] )
2195 return [targetView isEnabled];
2199 void wxWidgetCocoaImpl::Enable( bool enable )
2201 NSView* targetView = m_osxView;
2202 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2203 targetView = [(NSScrollView*) m_osxView documentView];
2205 if ( [targetView respondsToSelector:@selector(setEnabled:) ] )
2206 [targetView setEnabled:enable];
2209 void wxWidgetCocoaImpl::PulseGauge()
2213 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
2217 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
2219 NSControlSize size = NSRegularControlSize;
2223 case wxWINDOW_VARIANT_NORMAL :
2224 size = NSRegularControlSize;
2227 case wxWINDOW_VARIANT_SMALL :
2228 size = NSSmallControlSize;
2231 case wxWINDOW_VARIANT_MINI :
2232 size = NSMiniControlSize;
2235 case wxWINDOW_VARIANT_LARGE :
2236 size = NSRegularControlSize;
2240 wxFAIL_MSG(wxT("unexpected window variant"));
2243 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
2244 [m_osxView setControlSize:size];
2245 else if ([m_osxView respondsToSelector:@selector(cell)])
2247 id cell = [(id)m_osxView cell];
2248 if ([cell respondsToSelector:@selector(setControlSize:)])
2249 [cell setControlSize:size];
2253 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&col, long, bool)
2255 if ([m_osxView respondsToSelector:@selector(setFont:)])
2256 [m_osxView setFont: font.OSXGetNSFont()];
2257 if ([m_osxView respondsToSelector:@selector(setTextColor:)])
2258 [m_osxView setTextColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2259 green:(CGFloat) (col.Green() / 255.0)
2260 blue:(CGFloat) (col.Blue() / 255.0)
2261 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2264 void wxWidgetCocoaImpl::SetToolTip(wxToolTip* tooltip)
2268 wxCFStringRef cf( tooltip->GetTip() , m_wxPeer->GetFont().GetEncoding() );
2269 [m_osxView setToolTip: cf.AsNSString()];
2272 [m_osxView setToolTip: nil];
2276 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
2278 WXWidget c = control ? control : (WXWidget) m_osxView;
2279 wxWidgetImpl::Associate( c, this ) ;
2280 if ([c respondsToSelector:@selector(setAction:)])
2283 [c setAction: @selector(controlAction:)];
2284 if ([c respondsToSelector:@selector(setDoubleAction:)])
2286 [c setDoubleAction: @selector(controlDoubleAction:)];
2292 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
2294 wxKeyEvent wxevent(wxEVT_CHAR);
2295 SetupKeyEvent( wxevent, event, text );
2297 return GetWXPeer()->OSXHandleKeyEvent(wxevent);
2300 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
2302 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
2303 SetupKeyEvent( wxevent, event );
2305 // Generate wxEVT_CHAR_HOOK before sending any other events but only when
2306 // the key is pressed, not when it's released (the type of wxevent is
2307 // changed by SetupKeyEvent() so it can be wxEVT_KEY_UP too by now).
2308 if ( wxevent.GetEventType() == wxEVT_KEY_DOWN )
2310 wxKeyEvent eventHook(wxEVT_CHAR_HOOK, wxevent);
2311 if ( GetWXPeer()->OSXHandleKeyEvent(eventHook)
2312 && !eventHook.IsNextEventAllowed() )
2316 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
2318 // this will fire higher level events, like insertText, to help
2319 // us handle EVT_CHAR, etc.
2323 if ( IsUserPane() && [event type] == NSKeyDown)
2325 long keycode = wxOSXTranslateCocoaKey( event, wxEVT_CHAR );
2327 if ( (keycode > 0 && keycode < WXK_SPACE) || keycode == WXK_DELETE || keycode >= WXK_START )
2329 // eventually we could setup a doCommandBySelector catcher and retransform this into the wx key chars
2330 wxKeyEvent wxevent2(wxevent) ;
2331 wxevent2.SetEventType(wxEVT_CHAR);
2332 wxevent2.m_keyCode = keycode;
2333 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2337 if ( !wxevent.CmdDown() )
2339 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2340 [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
2342 [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
2352 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
2354 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
2355 SetupMouseEvent(wxevent , event) ;
2357 return GetWXPeer()->HandleWindowEvent(wxevent);
2360 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
2362 wxWindow* thisWindow = GetWXPeer();
2363 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
2365 thisWindow->MacInvalidateBorders();
2368 if ( receivedFocus )
2370 wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
2371 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
2372 thisWindow->HandleWindowEvent(eventFocus);
2375 if ( thisWindow->GetCaret() )
2376 thisWindow->GetCaret()->OnSetFocus();
2379 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
2380 event.SetEventObject(thisWindow);
2382 event.SetWindow(otherWindow->GetWXPeer());
2383 thisWindow->HandleWindowEvent(event) ;
2385 else // !receivedFocuss
2388 if ( thisWindow->GetCaret() )
2389 thisWindow->GetCaret()->OnKillFocus();
2392 wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
2394 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
2395 event.SetEventObject(thisWindow);
2397 event.SetWindow(otherWindow->GetWXPeer());
2398 thisWindow->HandleWindowEvent(event) ;
2402 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
2406 NSPoint location = [NSEvent mouseLocation];
2407 location = [[m_osxView window] convertScreenToBase:location];
2408 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
2410 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
2412 [(NSCursor*)cursor.GetHCURSOR() set];
2415 [[m_osxView window] invalidateCursorRectsForView:m_osxView];
2418 void wxWidgetCocoaImpl::CaptureMouse()
2420 [[m_osxView window] disableCursorRects];
2423 void wxWidgetCocoaImpl::ReleaseMouse()
2425 [[m_osxView window] enableCursorRects];
2428 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
2430 m_isFlipped = flipped;
2437 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
2438 wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
2439 long WXUNUSED(style), long WXUNUSED(extraStyle))
2441 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
2442 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
2444 // temporary hook for dnd
2445 [v registerForDraggedTypes:[NSArray arrayWithObjects:
2446 NSStringPboardType, NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSPDFPboardType, nil]];
2448 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v, false, true );
2452 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
2454 NSWindow* tlw = now->GetWXWindow();
2456 wxWidgetCocoaImpl* c = NULL;
2457 if ( now->IsNativeWindowWrapper() )
2459 NSView* cv = [tlw contentView];
2460 c = new wxWidgetCocoaImpl( now, cv, true );
2461 // increase ref count, because the impl destructor will decrement it again
2463 if ( !now->IsShown() )
2469 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2470 c = new wxWidgetCocoaImpl( now, v, true );
2471 c->InstallEventHandler();
2472 [tlw setContentView:v];