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
91 NSTrackingRectTag _lastToolTipTrackTag;
99 @interface NSView(PossibleMethods)
100 - (void)setTitle:(NSString *)aString;
101 - (void)setStringValue:(NSString *)aString;
102 - (void)setIntValue:(int)anInt;
103 - (void)setFloatValue:(float)aFloat;
104 - (void)setDoubleValue:(double)aDouble;
108 - (void)setMinValue:(double)aDouble;
109 - (void)setMaxValue:(double)aDouble;
114 - (void)setEnabled:(BOOL)flag;
116 - (void)setImage:(NSImage *)image;
117 - (void)setControlSize:(NSControlSize)size;
119 - (void)setFont:(NSFont *)fontObject;
123 - (void)setTarget:(id)anObject;
124 - (void)setAction:(SEL)aSelector;
125 - (void)setDoubleAction:(SEL)aSelector;
126 - (void)setBackgroundColor:(NSColor*)aColor;
127 - (void)setOpaque:(BOOL)opaque;
128 - (void)setTextColor:(NSColor *)color;
129 - (void)setImagePosition:(NSCellImagePosition)aPosition;
132 // The following code is a combination of the code listed here:
133 // http://lists.apple.com/archives/cocoa-dev/2008/Apr/msg01582.html
134 // (which can't be used because KLGetCurrentKeyboardLayout etc aren't 64-bit)
135 // and the code here:
136 // http://inquisitivecocoa.com/category/objective-c/
137 @interface NSEvent (OsGuiUtilsAdditions)
138 - (NSString*) charactersIgnoringModifiersIncludingShift;
141 @implementation NSEvent (OsGuiUtilsAdditions)
142 - (NSString*) charactersIgnoringModifiersIncludingShift {
143 // First try -charactersIgnoringModifiers and look for keys which UCKeyTranslate translates
144 // differently than AppKit.
145 NSString* c = [self charactersIgnoringModifiers];
146 if ([c length] == 1) {
147 unichar codepoint = [c characterAtIndex:0];
148 if ((codepoint >= 0xF700 && codepoint <= 0xF8FF) || codepoint == 0x7F) {
152 // This is not a "special" key, so ask UCKeyTranslate to give us the character with no
153 // modifiers attached. Actually, that's not quite accurate; we attach the Command modifier
154 // which hints the OS to use Latin characters where possible, which is generally what we want.
155 NSString* result = @"";
156 TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
157 CFDataRef uchr = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
158 CFRelease(currentKeyboard);
160 // this can happen for some non-U.S. input methods (eg. Romaji or Hiragana)
163 const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout*)CFDataGetBytePtr(uchr);
164 if (keyboardLayout) {
165 UInt32 deadKeyState = 0;
166 UniCharCount maxStringLength = 255;
167 UniCharCount actualStringLength = 0;
168 UniChar unicodeString[maxStringLength];
170 OSStatus status = UCKeyTranslate(keyboardLayout,
173 cmdKey >> 8, // force the Command key to "on"
175 kUCKeyTranslateNoDeadKeysMask,
182 result = [NSString stringWithCharacters:unicodeString length:(NSInteger)actualStringLength];
188 long wxOSXTranslateCocoaKey( NSEvent* event, int eventType )
192 if ([event type] != NSFlagsChanged)
194 NSString* s = [event charactersIgnoringModifiersIncludingShift];
195 // backspace char reports as delete w/modifiers for some reason
198 if ( eventType == wxEVT_CHAR && ([event modifierFlags] & NSControlKeyMask) && ( [s characterAtIndex:0] >= 'a' && [s characterAtIndex:0] <= 'z' ) )
200 retval = WXK_CONTROL_A + ([s characterAtIndex:0] - 'a');
204 switch ( [s characterAtIndex:0] )
211 case NSUpArrowFunctionKey :
214 case NSDownArrowFunctionKey :
217 case NSLeftArrowFunctionKey :
220 case NSRightArrowFunctionKey :
223 case NSInsertFunctionKey :
226 case NSDeleteFunctionKey :
229 case NSHomeFunctionKey :
232 // case NSBeginFunctionKey :
233 // retval = WXK_BEGIN;
235 case NSEndFunctionKey :
238 case NSPageUpFunctionKey :
241 case NSPageDownFunctionKey :
242 retval = WXK_PAGEDOWN;
244 case NSHelpFunctionKey :
248 int intchar = [s characterAtIndex: 0];
249 if ( intchar >= NSF1FunctionKey && intchar <= NSF24FunctionKey )
250 retval = WXK_F1 + (intchar - NSF1FunctionKey );
251 else if ( intchar > 0 && intchar < 32 )
259 // Some keys don't seem to have constants. The code mimics the approach
260 // taken by WebKit. See:
261 // http://trac.webkit.org/browser/trunk/WebCore/platform/mac/KeyEventMac.mm
262 switch( [event keyCode] )
267 retval = WXK_CONTROL;
271 retval = WXK_CAPITAL;
274 case 56: // Left Shift
275 case 60: // Right Shift
280 case 61: // Right Alt
284 case 59: // Left Ctrl
285 case 62: // Right Ctrl
286 retval = WXK_RAW_CONTROL;
298 retval = WXK_NUMPAD_DIVIDE;
301 retval = WXK_NUMPAD_MULTIPLY;
304 retval = WXK_NUMPAD_SUBTRACT;
307 retval = WXK_NUMPAD_ADD;
310 retval = WXK_NUMPAD_ENTER;
313 retval = WXK_NUMPAD_DECIMAL;
316 retval = WXK_NUMPAD0;
319 retval = WXK_NUMPAD1;
322 retval = WXK_NUMPAD2;
325 retval = WXK_NUMPAD3;
328 retval = WXK_NUMPAD4;
331 retval = WXK_NUMPAD5;
334 retval = WXK_NUMPAD6;
337 retval = WXK_NUMPAD7;
340 retval = WXK_NUMPAD8;
343 retval = WXK_NUMPAD9;
346 //retval = [event keyCode];
352 void wxWidgetCocoaImpl::SetupKeyEvent(wxKeyEvent &wxevent , NSEvent * nsEvent, NSString* charString)
354 UInt32 modifiers = [nsEvent modifierFlags] ;
355 int eventType = [nsEvent type];
357 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
358 wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
359 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
360 wxevent.m_controlDown = modifiers & NSCommandKeyMask;
362 wxevent.m_rawCode = [nsEvent keyCode];
363 wxevent.m_rawFlags = modifiers;
365 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
368 if ( eventType != NSFlagsChanged )
370 NSString* nschars = [[nsEvent charactersIgnoringModifiersIncludingShift] uppercaseString];
373 // if charString is set, it did not come from key up / key down
374 wxevent.SetEventType( wxEVT_CHAR );
375 chars = wxCFStringRef::AsString(charString);
379 chars = wxCFStringRef::AsString(nschars);
383 int aunichar = chars.Length() > 0 ? chars[0] : 0;
386 if (wxevent.GetEventType() != wxEVT_CHAR)
388 keyval = wxOSXTranslateCocoaKey(nsEvent, wxevent.GetEventType()) ;
392 wxevent.SetEventType( wxEVT_KEY_DOWN ) ;
395 wxevent.SetEventType( wxEVT_KEY_UP ) ;
397 case NSFlagsChanged :
401 wxevent.SetEventType( wxevent.m_controlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
404 wxevent.SetEventType( wxevent.m_shiftDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
407 wxevent.SetEventType( wxevent.m_altDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
409 case WXK_RAW_CONTROL:
410 wxevent.SetEventType( wxevent.m_rawControlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
421 if ( wxevent.GetEventType() == wxEVT_KEY_UP || wxevent.GetEventType() == wxEVT_KEY_DOWN )
422 keyval = wxToupper( aunichar ) ;
428 // OS X generates events with key codes in Unicode private use area for
429 // unprintable symbols such as cursor arrows (WXK_UP is mapped to U+F700)
430 // and function keys (WXK_F2 is U+F705). We don't want to use them as the
431 // result of wxKeyEvent::GetUnicodeKey() however as it's supposed to return
432 // WXK_NONE for "non characters" so explicitly exclude them.
434 // We only exclude the private use area inside the Basic Multilingual Plane
435 // as key codes beyond it don't seem to be currently used.
436 if ( !(aunichar >= 0xe000 && aunichar < 0xf900) )
437 wxevent.m_uniChar = aunichar;
439 wxevent.m_keyCode = keyval;
441 wxWindowMac* peer = GetWXPeer();
444 wxevent.SetEventObject(peer);
445 wxevent.SetId(peer->GetId()) ;
449 UInt32 g_lastButton = 0 ;
450 bool g_lastButtonWasFakeRight = false ;
452 // better scroll wheel support
453 // see http://lists.apple.com/archives/cocoa-dev/2007/Feb/msg00050.html
455 @interface NSEvent (DeviceDelta)
456 - (CGFloat)deviceDeltaX;
457 - (CGFloat)deviceDeltaY;
460 - (BOOL)hasPreciseScrollingDeltas;
461 - (CGFloat)scrollingDeltaX;
462 - (CGFloat)scrollingDeltaY;
465 void wxWidgetCocoaImpl::SetupMouseEvent( wxMouseEvent &wxevent , NSEvent * nsEvent )
467 int eventType = [nsEvent type];
468 UInt32 modifiers = [nsEvent modifierFlags] ;
470 NSPoint locationInWindow = [nsEvent locationInWindow];
472 // adjust coordinates for the window of the target view
473 if ( [nsEvent window] != [m_osxView window] )
475 if ( [nsEvent window] != nil )
476 locationInWindow = [[nsEvent window] convertBaseToScreen:locationInWindow];
478 if ( [m_osxView window] != nil )
479 locationInWindow = [[m_osxView window] convertScreenToBase:locationInWindow];
482 NSPoint locationInView = [m_osxView convertPoint:locationInWindow fromView:nil];
483 wxPoint locationInViewWX = wxFromNSPoint( m_osxView, locationInView );
485 // these parameters are not given for all events
486 UInt32 button = [nsEvent buttonNumber];
487 UInt32 clickCount = 0;
489 wxevent.m_x = locationInViewWX.x;
490 wxevent.m_y = locationInViewWX.y;
491 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
492 wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
493 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
494 wxevent.m_controlDown = modifiers & NSCommandKeyMask;
495 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
497 UInt32 mouseChord = 0;
501 case NSLeftMouseDown :
502 case NSLeftMouseDragged :
505 case NSRightMouseDown :
506 case NSRightMouseDragged :
509 case NSOtherMouseDown :
510 case NSOtherMouseDragged :
515 // a control click is interpreted as a right click
516 bool thisButtonIsFakeRight = false ;
517 if ( button == 0 && (modifiers & NSControlKeyMask) )
520 thisButtonIsFakeRight = true ;
523 // otherwise we report double clicks by connecting a left click with a ctrl-left click
524 if ( clickCount > 1 && button != g_lastButton )
527 // we must make sure that our synthetic 'right' button corresponds in
528 // mouse down, moved and mouse up, and does not deliver a right down and left up
531 case NSLeftMouseDown :
532 case NSRightMouseDown :
533 case NSOtherMouseDown :
534 g_lastButton = button ;
535 g_lastButtonWasFakeRight = thisButtonIsFakeRight ;
542 g_lastButtonWasFakeRight = false ;
544 else if ( g_lastButton == 1 && g_lastButtonWasFakeRight )
545 button = g_lastButton ;
547 // Adjust the chord mask to remove the primary button and add the
548 // secondary button. It is possible that the secondary button is
549 // already pressed, e.g. on a mouse connected to a laptop, but this
550 // possibility is ignored here:
551 if( thisButtonIsFakeRight && ( mouseChord & 1U ) )
552 mouseChord = ((mouseChord & ~1U) | 2U);
555 wxevent.m_leftDown = true ;
557 wxevent.m_rightDown = true ;
559 wxevent.m_middleDown = true ;
561 // translate into wx types
564 case NSLeftMouseDown :
565 case NSRightMouseDown :
566 case NSOtherMouseDown :
567 clickCount = [nsEvent clickCount];
571 wxevent.SetEventType( clickCount > 1 ? wxEVT_LEFT_DCLICK : wxEVT_LEFT_DOWN ) ;
575 wxevent.SetEventType( clickCount > 1 ? wxEVT_RIGHT_DCLICK : wxEVT_RIGHT_DOWN ) ;
579 wxevent.SetEventType( clickCount > 1 ? wxEVT_MIDDLE_DCLICK : wxEVT_MIDDLE_DOWN ) ;
588 case NSRightMouseUp :
589 case NSOtherMouseUp :
590 clickCount = [nsEvent clickCount];
594 wxevent.SetEventType( wxEVT_LEFT_UP ) ;
598 wxevent.SetEventType( wxEVT_RIGHT_UP ) ;
602 wxevent.SetEventType( wxEVT_MIDDLE_UP ) ;
615 wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ;
617 if ( UMAGetSystemVersion() >= 0x1070 )
619 if ( [nsEvent hasPreciseScrollingDeltas] )
621 deltaX = [nsEvent scrollingDeltaX];
622 deltaY = [nsEvent scrollingDeltaY];
626 deltaX = [nsEvent scrollingDeltaX] * 10;
627 deltaY = [nsEvent scrollingDeltaY] * 10;
632 const EventRef cEvent = (EventRef) [nsEvent eventRef];
633 // see http://developer.apple.com/qa/qa2005/qa1453.html
634 // for more details on why we have to look for the exact type
636 bool isMouseScrollEvent = false;
638 isMouseScrollEvent = ::GetEventKind(cEvent) == kEventMouseScroll;
640 if ( isMouseScrollEvent )
642 deltaX = [nsEvent deviceDeltaX];
643 deltaY = [nsEvent deviceDeltaY];
647 deltaX = ([nsEvent deltaX] * 10);
648 deltaY = ([nsEvent deltaY] * 10);
652 wxevent.m_wheelDelta = 10;
653 wxevent.m_linesPerAction = 1;
655 if ( fabs(deltaX) > fabs(deltaY) )
657 wxevent.m_wheelAxis = wxMOUSE_WHEEL_HORIZONTAL;
658 wxevent.m_wheelRotation = (int)deltaX;
662 wxevent.m_wheelRotation = (int)deltaY;
668 case NSMouseEntered :
669 wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
672 wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
674 case NSLeftMouseDragged :
675 case NSRightMouseDragged :
676 case NSOtherMouseDragged :
678 wxevent.SetEventType( wxEVT_MOTION ) ;
684 wxevent.m_clickCount = clickCount;
685 wxWindowMac* peer = GetWXPeer();
688 wxevent.SetEventObject(peer);
689 wxevent.SetId(peer->GetId()) ;
693 @implementation wxNSView
697 static BOOL initialized = NO;
701 wxOSXCocoaClassAddWXMethods( self );
705 /* idea taken from webkit sources: overwrite the methods that (private) NSToolTipManager will use to attach its tracking rectangle
706 * then when changing the tooltip send fake view-exit and view-enter methods which will lead to a tooltip refresh
710 - (void)_sendToolTipMouseExited
712 // Nothing matters except window, trackingNumber, and userData.
713 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
714 location:NSMakePoint(0, 0)
717 windowNumber:[[self window] windowNumber]
720 trackingNumber:_lastToolTipTrackTag
721 userData:_lastUserData];
722 [_lastToolTipOwner mouseExited:fakeEvent];
725 - (void)_sendToolTipMouseEntered
727 // Nothing matters except window, trackingNumber, and userData.
728 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
729 location:NSMakePoint(0, 0)
732 windowNumber:[[self window] windowNumber]
735 trackingNumber:_lastToolTipTrackTag
736 userData:_lastUserData];
737 [_lastToolTipOwner mouseEntered:fakeEvent];
740 - (void)setToolTip:(NSString *)string;
746 [self _sendToolTipMouseExited];
749 [super setToolTip:string];
751 [self _sendToolTipMouseEntered];
757 [self _sendToolTipMouseExited];
758 [super setToolTip:nil];
764 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
766 NSTrackingRectTag tag = [super addTrackingRect:rect owner:owner userData:data assumeInside:assumeInside];
769 _lastUserData = data;
770 _lastToolTipOwner = owner;
771 _lastToolTipTrackTag = tag;
776 - (void)removeTrackingRect:(NSTrackingRectTag)tag
778 if (tag == _lastToolTipTrackTag)
780 _lastUserData = NULL;
781 _lastToolTipOwner = nil;
782 _lastToolTipTrackTag = 0;
784 [super removeTrackingRect:tag];
792 #if wxUSE_DRAG_AND_DROP
794 // see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
795 // for details on the NSPasteboard -> PasteboardRef conversion
797 NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
799 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
801 return NSDragOperationNone;
803 return impl->draggingEntered(sender, self, _cmd);
806 void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
808 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
812 return impl->draggingExited(sender, self, _cmd);
815 NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
817 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
819 return NSDragOperationNone;
821 return impl->draggingUpdated(sender, self, _cmd);
824 BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
826 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
828 return NSDragOperationNone;
830 return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
835 void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
837 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
841 impl->mouseEvent(event, self, _cmd);
844 void wxOSX_cursorUpdate(NSView* self, SEL _cmd, NSEvent *event)
846 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
850 impl->cursorUpdate(event, self, _cmd);
853 BOOL wxOSX_acceptsFirstMouse(NSView* WXUNUSED(self), SEL WXUNUSED(_cmd), NSEvent *WXUNUSED(event))
855 // This is needed to support click through, otherwise the first click on a window
856 // will not do anything unless it is the active window already.
860 void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
862 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
866 impl->keyEvent(event, self, _cmd);
869 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
871 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
875 impl->insertText(text, self, _cmd);
878 BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
880 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
884 return impl->performKeyEquivalent(event, self, _cmd);
887 BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
889 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
893 return impl->acceptsFirstResponder(self, _cmd);
896 BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
898 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
902 return impl->becomeFirstResponder(self, _cmd);
905 BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
907 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
911 return impl->resignFirstResponder(self, _cmd);
914 BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
916 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
920 return impl->isFlipped(self, _cmd) ? YES:NO;
923 typedef void (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
925 void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
927 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
932 // OS X starts a NSUIHeartBeatThread for animating the default button in a
933 // dialog. This causes a drawRect of the active dialog from outside the
934 // main UI thread. This causes an occasional crash since the wx drawing
935 // objects (like wxPen) are not thread safe.
937 // Notice that NSUIHeartBeatThread seems to be undocumented and doing
938 // [NSWindow setAllowsConcurrentViewDrawing:NO] does not affect it.
939 if ( !wxThread::IsMain() )
941 if ( impl->IsUserPane() )
943 wxWindow* win = impl->GetWXPeer();
944 if ( win->UseBgCol() )
947 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
948 CGContextSaveGState( context );
950 CGContextSetFillColorWithColor( context, win->GetBackgroundColour().GetCGColor());
951 CGRect r = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
952 CGContextFillRect( context, r );
954 CGContextRestoreGState( context );
959 // just call the superclass handler, we don't need any custom wx drawing
960 // here and it seems to work fine:
961 wxOSX_DrawRectHandlerPtr
962 superimpl = (wxOSX_DrawRectHandlerPtr)
963 [[self superclass] instanceMethodForSelector:_cmd];
964 superimpl(self, _cmd, rect);
969 #endif // wxUSE_THREADS
971 return impl->drawRect(&rect, self, _cmd);
974 void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
976 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
980 impl->controlAction(self, _cmd, sender);
983 void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
985 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
989 impl->controlDoubleAction(self, _cmd, sender);
992 unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
994 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
995 NSPasteboard *pboard = [sender draggingPasteboard];
996 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
998 wxWindow* wxpeer = GetWXPeer();
999 if ( wxpeer == NULL )
1000 return NSDragOperationNone;
1002 wxDropTarget* target = wxpeer->GetDropTarget();
1003 if ( target == NULL )
1004 return NSDragOperationNone;
1006 wxDragResult result = wxDragNone;
1007 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1008 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1010 if ( sourceDragMask & NSDragOperationLink )
1011 result = wxDragLink;
1012 else if ( sourceDragMask & NSDragOperationCopy )
1013 result = wxDragCopy;
1014 else if ( sourceDragMask & NSDragOperationMove )
1015 result = wxDragMove;
1017 PasteboardRef pboardRef;
1018 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1019 target->SetCurrentDragPasteboard(pboardRef);
1020 result = target->OnEnter(pt.x, pt.y, result);
1021 CFRelease(pboardRef);
1023 NSDragOperation nsresult = NSDragOperationNone;
1027 nsresult = NSDragOperationLink;
1029 nsresult = NSDragOperationMove;
1031 nsresult = NSDragOperationCopy;
1038 void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1040 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1041 NSPasteboard *pboard = [sender draggingPasteboard];
1043 wxWindow* wxpeer = GetWXPeer();
1044 if ( wxpeer == NULL )
1047 wxDropTarget* target = wxpeer->GetDropTarget();
1048 if ( target == NULL )
1051 PasteboardRef pboardRef;
1052 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1053 target->SetCurrentDragPasteboard(pboardRef);
1055 CFRelease(pboardRef);
1058 unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1060 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1061 NSPasteboard *pboard = [sender draggingPasteboard];
1062 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1064 wxWindow* wxpeer = GetWXPeer();
1065 if ( wxpeer == NULL )
1066 return NSDragOperationNone;
1068 wxDropTarget* target = wxpeer->GetDropTarget();
1069 if ( target == NULL )
1070 return NSDragOperationNone;
1072 wxDragResult result = wxDragNone;
1073 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1074 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1076 if ( sourceDragMask & NSDragOperationLink )
1077 result = wxDragLink;
1078 else if ( sourceDragMask & NSDragOperationCopy )
1079 result = wxDragCopy;
1080 else if ( sourceDragMask & NSDragOperationMove )
1081 result = wxDragMove;
1083 PasteboardRef pboardRef;
1084 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1085 target->SetCurrentDragPasteboard(pboardRef);
1086 result = target->OnDragOver(pt.x, pt.y, result);
1087 CFRelease(pboardRef);
1089 NSDragOperation nsresult = NSDragOperationNone;
1093 nsresult = NSDragOperationLink;
1095 nsresult = NSDragOperationMove;
1097 nsresult = NSDragOperationCopy;
1104 bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1106 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1108 NSPasteboard *pboard = [sender draggingPasteboard];
1109 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1111 wxWindow* wxpeer = GetWXPeer();
1112 wxDropTarget* target = wxpeer->GetDropTarget();
1113 wxDragResult result = wxDragNone;
1114 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1115 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1117 if ( sourceDragMask & NSDragOperationLink )
1118 result = wxDragLink;
1119 else if ( sourceDragMask & NSDragOperationCopy )
1120 result = wxDragCopy;
1121 else if ( sourceDragMask & NSDragOperationMove )
1122 result = wxDragMove;
1124 PasteboardRef pboardRef;
1125 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1126 target->SetCurrentDragPasteboard(pboardRef);
1128 if (target->OnDrop(pt.x, pt.y))
1129 result = target->OnData(pt.x, pt.y, result);
1131 CFRelease(pboardRef);
1133 return result != wxDragNone;
1136 typedef void (*wxOSX_TextEventHandlerPtr)(NSView* self, SEL _cmd, NSString *event);
1137 typedef void (*wxOSX_EventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
1138 typedef BOOL (*wxOSX_PerformKeyEventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
1139 typedef BOOL (*wxOSX_FocusHandlerPtr)(NSView* self, SEL _cmd);
1141 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1143 if ( !DoHandleMouseEvent(event) )
1145 // for plain NSView mouse events would propagate to parents otherwise
1148 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1149 superimpl(slf, (SEL)_cmd, event);
1151 // super of built-ins keeps the mouse up, as wx expects this event, we have to synthesize it
1153 if ( [ event type] == NSLeftMouseDown )
1155 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
1156 SetupMouseEvent(wxevent , event) ;
1157 wxevent.SetEventType(wxEVT_LEFT_UP);
1159 GetWXPeer()->HandleWindowEvent(wxevent);
1165 void wxWidgetCocoaImpl::cursorUpdate(WX_NSEvent event, WXWidget slf, void *_cmd)
1167 NSCursor *cursor = (NSCursor*)GetWXPeer()->GetCursor().GetHCURSOR();
1170 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1171 superimpl(slf, (SEL)_cmd, event);
1181 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1183 if ( [event type] == NSKeyDown )
1185 // there are key equivalents that are not command-combos and therefore not handled by cocoa automatically,
1186 // therefore we call the menubar directly here, exit if the menu is handling the shortcut
1187 if ( [[[NSApplication sharedApplication] mainMenu] performKeyEquivalent:event] )
1190 m_lastKeyDownEvent = event;
1193 if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
1195 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1196 superimpl(slf, (SEL)_cmd, event);
1198 m_lastKeyDownEvent = NULL;
1201 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
1203 if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
1205 wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1206 superimpl(slf, (SEL)_cmd, text);
1211 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
1213 bool handled = false;
1215 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1216 SetupKeyEvent( wxevent, event );
1218 // because performKeyEquivalent is going up the entire view hierarchy, we don't have to
1219 // walk up the ancestors ourselves but let cocoa do it
1221 int command = m_wxPeer->GetAcceleratorTable()->GetCommand( wxevent );
1224 wxEvtHandler * const handler = m_wxPeer->GetEventHandler();
1226 wxCommandEvent command_event( wxEVT_COMMAND_MENU_SELECTED, command );
1227 command_event.SetEventObject( wxevent.GetEventObject() );
1228 handled = handler->ProcessEvent( command_event );
1232 // accelerators can also be used with buttons, try them too
1233 command_event.SetEventType(wxEVT_COMMAND_BUTTON_CLICKED);
1234 handled = handler->ProcessEvent( command_event );
1240 wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1241 return superimpl(slf, (SEL)_cmd, event);
1246 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
1249 return m_wxPeer->AcceptsFocus();
1252 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1253 return superimpl(slf, (SEL)_cmd);
1257 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
1259 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1260 // get the current focus before running becomeFirstResponder
1261 NSView* otherView = FindFocus();
1263 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1264 BOOL r = superimpl(slf, (SEL)_cmd);
1267 DoNotifyFocusEvent( true, otherWindow );
1273 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
1275 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1276 BOOL r = superimpl(slf, (SEL)_cmd);
1277 // get the current focus after running resignFirstResponder
1278 // note that this value isn't reliable, it might return the same view that
1280 NSView* otherView = FindFocus();
1281 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1283 // It doesn't make sense to notify about the loss of focus if we're not
1284 // really losing it and the window which has just gained focus is the same
1285 // one as this window itself. Of course, this should never happen in the
1286 // first place but somehow it does in wxGrid code and without this check we
1287 // enter into an infinite recursion, see #12267.
1288 if ( otherWindow == this )
1291 // NSTextViews have an editor as true responder, therefore the might get the
1292 // resign notification if their editor takes over, don't trigger any event then
1293 if ( r && !m_hasEditor)
1295 DoNotifyFocusEvent( false, otherWindow );
1300 bool wxWidgetCocoaImpl::isFlipped(WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1306 #define OSX_DEBUG_DRAWING 0
1308 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
1310 // preparing the update region
1313 const NSRect *rects;
1316 [slf getRectsBeingDrawn:&rects count:&count];
1317 for ( int i = 0 ; i < count ; ++i )
1319 updateRgn.Union(wxFromNSRect(slf, rects[i]));
1322 wxWindow* wxpeer = GetWXPeer();
1324 if ( wxpeer->MacGetLeftBorderSize() != 0 || wxpeer->MacGetTopBorderSize() != 0 )
1326 // as this update region is in native window locals we must adapt it to wx window local
1327 updateRgn.Offset( wxpeer->MacGetLeftBorderSize() , wxpeer->MacGetTopBorderSize() );
1330 // Restrict the update region to the shape of the window, if any, and also
1331 // remember the region that we need to clear later.
1332 wxNonOwnedWindow* const tlwParent = wxpeer->MacGetTopLevelWindow();
1333 const bool isTopLevel = tlwParent == wxpeer;
1335 if ( tlwParent->GetWindowStyle() & wxFRAME_SHAPED )
1338 clearRgn = updateRgn;
1340 int xoffset = 0, yoffset = 0;
1341 wxRegion rgn = tlwParent->GetShape();
1342 wxpeer->MacRootWindowToWindow( &xoffset, &yoffset );
1343 rgn.Offset( xoffset, yoffset );
1344 updateRgn.Intersect(rgn);
1348 // Exclude the window shape from the region to be cleared below.
1349 rgn.Xor(wxpeer->GetSize());
1350 clearRgn.Intersect(rgn);
1354 wxpeer->GetUpdateRegion() = updateRgn;
1356 // setting up the drawing context
1358 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1359 CGContextSaveGState( context );
1361 #if OSX_DEBUG_DRAWING
1362 CGContextBeginPath( context );
1363 CGContextMoveToPoint(context, 0, 0);
1364 NSRect bounds = [slf bounds];
1365 CGContextAddLineToPoint(context, 10, 0);
1366 CGContextMoveToPoint(context, 0, 0);
1367 CGContextAddLineToPoint(context, 0, 10);
1368 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1369 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1370 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1371 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1372 CGContextClosePath( context );
1373 CGContextStrokePath(context);
1378 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1379 CGContextScaleCTM( context, 1, -1 );
1382 wxpeer->MacSetCGContextRef( context );
1384 bool handled = wxpeer->MacDoRedraw( 0 );
1385 CGContextRestoreGState( context );
1387 CGContextSaveGState( context );
1391 SEL _cmd = @selector(drawRect:);
1392 wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1393 superimpl(slf, _cmd, *(NSRect*)rect);
1394 CGContextRestoreGState( context );
1395 CGContextSaveGState( context );
1397 // as we called restore above, we have to flip again if necessary
1400 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1401 CGContextScaleCTM( context, 1, -1 );
1406 // We also need to explicitly draw the part of the top level window
1407 // outside of its region with transparent colour to ensure that it is
1408 // really transparent.
1409 if ( clearRgn.IsOk() )
1411 wxMacCGContextStateSaver saveState(context);
1412 wxWindowDC dc(wxpeer);
1413 dc.SetBackground(wxBrush(wxTransparentColour));
1414 dc.SetDeviceClippingRegion(clearRgn);
1418 #if wxUSE_GRAPHICS_CONTEXT
1419 // If the window shape is defined by a path, stroke the path to show
1420 // the window border.
1421 const wxGraphicsPath& path = tlwParent->GetShapePath();
1422 if ( !path.IsNull() )
1424 CGContextSetLineWidth(context, 1);
1425 CGContextSetStrokeColorWithColor(context, wxLIGHT_GREY->GetCGColor());
1426 CGContextAddPath(context, (CGPathRef) path.GetNativePath());
1427 CGContextStrokePath(context);
1429 #endif // wxUSE_GRAPHICS_CONTEXT
1432 wxpeer->MacPaintChildrenBorders();
1433 wxpeer->MacSetCGContextRef( NULL );
1434 CGContextRestoreGState( context );
1437 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1439 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1442 wxpeer->OSXSimulateFocusEvents();
1443 wxpeer->OSXHandleClicked(0);
1447 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1451 void wxWidgetCocoaImpl::controlTextDidChange()
1453 wxWindow* wxpeer = (wxWindow*)GetWXPeer();
1456 // since native rtti doesn't have to be enabled and wx' rtti is not aware of the mixin wxTextEntry, workaround is needed
1457 wxTextCtrl *tc = wxDynamicCast( wxpeer , wxTextCtrl );
1458 wxComboBox *cb = wxDynamicCast( wxpeer , wxComboBox );
1460 tc->SendTextUpdatedEventIfAllowed();
1462 cb->SendTextUpdatedEventIfAllowed();
1465 wxFAIL_MSG("Unexpected class for controlTextDidChange event");
1472 #if OBJC_API_VERSION >= 2
1474 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1475 class_addMethod(c, s, i, t );
1479 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1480 { s, (char*) t, i },
1484 void wxOSXCocoaClassAddWXMethods(Class c)
1487 #if OBJC_API_VERSION < 2
1488 static objc_method wxmethods[] =
1492 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1493 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1494 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1496 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1497 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1498 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1500 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1502 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1503 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1504 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1506 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
1508 wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1509 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1510 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1512 wxOSX_CLASS_ADD_METHOD(c, @selector(cursorUpdate:), (IMP) wxOSX_cursorUpdate, "v@:@" )
1514 wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1515 wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1516 wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1518 wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1520 wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
1522 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1523 wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1524 wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1526 wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1527 wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1529 wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1530 wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1532 #if wxUSE_DRAG_AND_DROP
1533 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1534 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1535 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1536 wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1539 #if OBJC_API_VERSION < 2
1541 static int method_count = WXSIZEOF( wxmethods );
1542 static objc_method_list *wxmethodlist = NULL;
1543 if ( wxmethodlist == NULL )
1545 wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1546 memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1547 wxmethodlist->method_count = method_count;
1548 wxmethodlist->obsolete = 0;
1550 class_addMethods( c, wxmethodlist );
1555 // C++ implementation class
1558 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1560 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl, bool isUserPane ) :
1561 wxWidgetImpl( peer, isRootControl, isUserPane )
1566 // check if the user wants to create the control initially hidden
1567 if ( !peer->IsShown() )
1568 SetVisibility(false);
1570 // gc aware handling
1572 CFRetain(m_osxView);
1573 [m_osxView release];
1576 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1581 void wxWidgetCocoaImpl::Init()
1585 m_lastKeyDownEvent = NULL;
1586 m_hasEditor = false;
1589 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1591 RemoveAssociations( this );
1593 if ( !IsRootControl() )
1595 NSView *sv = [m_osxView superview];
1597 [m_osxView removeFromSuperview];
1599 // gc aware handling
1601 CFRelease(m_osxView);
1604 bool wxWidgetCocoaImpl::IsVisible() const
1606 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1609 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1611 [m_osxView setHidden:(visible ? NO:YES)];
1614 // ----------------------------------------------------------------------------
1615 // window animation stuff
1616 // ----------------------------------------------------------------------------
1618 // define a delegate used to refresh the window during animation
1619 @interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
1625 - (id)init:(wxWindow *)win;
1629 // NSAnimationDelegate methods
1630 - (void)animationDidEnd:(NSAnimation*)animation;
1631 - (void)animation:(NSAnimation*)animation
1632 didReachProgressMark:(NSAnimationProgress)progress;
1635 @implementation wxNSAnimationDelegate
1637 - (id)init:(wxWindow *)win
1639 self = [super init];
1652 - (void)animation:(NSAnimation*)animation
1653 didReachProgressMark:(NSAnimationProgress)progress
1655 wxUnusedVar(animation);
1656 wxUnusedVar(progress);
1658 m_win->SendSizeEvent();
1659 m_win->MacOnInternalSize();
1662 - (void)animationDidEnd:(NSAnimation*)animation
1664 wxUnusedVar(animation);
1672 wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1674 wxShowEffect effect,
1677 // create the dictionary describing the animation to perform on this view
1679 viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1680 NSMutableDictionary * const
1681 dict = [NSMutableDictionary dictionaryWithCapacity:4];
1682 [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1684 // determine the start and end rectangles assuming we're hiding the window
1685 const wxRect rectOrig = win->GetRect();
1693 if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1694 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1695 effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1696 else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1697 effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1698 effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1699 else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1700 effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1701 effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1702 else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1703 effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1704 effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1709 case wxSHOW_EFFECT_ROLL_TO_LEFT:
1710 case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1714 case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1715 case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1716 rectEnd.x = rectStart.GetRight();
1720 case wxSHOW_EFFECT_ROLL_TO_TOP:
1721 case wxSHOW_EFFECT_SLIDE_TO_TOP:
1725 case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1726 case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1727 rectEnd.y = rectStart.GetBottom();
1731 case wxSHOW_EFFECT_EXPAND:
1732 rectEnd.x = rectStart.x + rectStart.width / 2;
1733 rectEnd.y = rectStart.y + rectStart.height / 2;
1738 case wxSHOW_EFFECT_BLEND:
1739 [dict setObject:(show ? NSViewAnimationFadeInEffect
1740 : NSViewAnimationFadeOutEffect)
1741 forKey:NSViewAnimationEffectKey];
1744 case wxSHOW_EFFECT_NONE:
1745 case wxSHOW_EFFECT_MAX:
1746 wxFAIL_MSG( "unexpected animation effect" );
1750 wxFAIL_MSG( "unknown animation effect" );
1756 // we need to restore it to the original rectangle instead of making it
1758 wxSwap(rectStart, rectEnd);
1760 // and as the window is currently hidden, we need to show it for the
1761 // animation to be visible at all (but don't restore it at its full
1762 // rectangle as it shouldn't appear immediately)
1763 win->SetSize(rectStart);
1767 NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1768 ? [(NSView *)viewOrWin superview]
1770 const NSRect rStart = wxToNSRect(parentView, rectStart);
1771 const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1773 [dict setObject:[NSValue valueWithRect:rStart]
1774 forKey:NSViewAnimationStartFrameKey];
1775 [dict setObject:[NSValue valueWithRect:rEnd]
1776 forKey:NSViewAnimationEndFrameKey];
1778 // create an animation using the values in the above dictionary
1779 NSViewAnimation * const
1780 anim = [[NSViewAnimation alloc]
1781 initWithViewAnimations:[NSArray arrayWithObject:dict]];
1785 // what is a good default duration? Windows uses 200ms, Web frameworks
1786 // use anything from 250ms to 1s... choose something in the middle
1790 [anim setDuration:timeout/1000.]; // duration is in seconds here
1792 // if the window being animated changes its layout depending on its size
1793 // (which is almost always the case) we need to redo it during animation
1795 // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1796 // controls in wxInfoBar visibly jump around)
1797 const int NUM_LAYOUTS = 20;
1798 for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1799 [anim addProgressMark:f];
1801 wxNSAnimationDelegate * const
1802 animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1803 [anim setDelegate:animDelegate];
1804 [anim startAnimation];
1806 // Cocoa is capable of doing animation asynchronously or even from separate
1807 // thread but wx API doesn't provide any way to be notified about the
1808 // animation end and without this we really must ensure that the window has
1809 // the expected (i.e. the same as if a simple Show() had been used) size
1810 // when we return, so block here until the animation finishes
1812 // notice that because the default animation mode is NSAnimationBlocking,
1813 // no user input events ought to be processed from here
1815 wxEventLoopGuarantor ensureEventLoopExistence;
1816 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1817 while ( ![animDelegate isDone] )
1823 // NSViewAnimation is smart enough to hide the NSView being animated at
1824 // the end but we also must ensure that it's hidden for wx too
1827 // and we must also restore its size because it isn't expected to
1828 // change just because the window was hidden
1829 win->SetSize(rectOrig);
1833 // refresh it once again after the end to ensure that everything is in
1835 win->SendSizeEvent();
1836 win->MacOnInternalSize();
1839 [anim setDelegate:nil];
1840 [animDelegate release];
1846 bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
1847 wxShowEffect effect,
1850 return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
1853 /* note that the drawing order between siblings is not defined under 10.4 */
1854 /* only starting from 10.5 the subview order is respected */
1856 /* NSComparisonResult is typedef'd as an enum pre-Leopard but typedef'd as
1857 * NSInteger post-Leopard. Pre-Leopard the Cocoa toolkit expects a function
1858 * returning int and not NSComparisonResult. Post-Leopard the Cocoa toolkit
1859 * expects a function returning the new non-enum NSComparsionResult.
1860 * Hence we create a typedef named CocoaWindowCompareFunctionResult.
1862 #if defined(NSINTEGER_DEFINED)
1863 typedef NSComparisonResult CocoaWindowCompareFunctionResult;
1865 typedef int CocoaWindowCompareFunctionResult;
1868 class CocoaWindowCompareContext
1870 wxDECLARE_NO_COPY_CLASS(CocoaWindowCompareContext);
1872 CocoaWindowCompareContext(); // Not implemented
1873 CocoaWindowCompareContext(NSView *target, NSArray *subviews)
1876 // Cocoa sorts subviews in-place.. make a copy
1877 m_subviews = [subviews copy];
1880 ~CocoaWindowCompareContext()
1881 { // release the copy
1882 [m_subviews release];
1885 { return m_target; }
1888 { return m_subviews; }
1890 /* Helper function that returns the comparison based off of the original ordering */
1891 CocoaWindowCompareFunctionResult CompareUsingOriginalOrdering(id first, id second)
1893 NSUInteger firstI = [m_subviews indexOfObjectIdenticalTo:first];
1894 NSUInteger secondI = [m_subviews indexOfObjectIdenticalTo:second];
1895 // NOTE: If either firstI or secondI is NSNotFound then it will be NSIntegerMax and thus will
1896 // likely compare higher than the other view which is reasonable considering the only way that
1897 // can happen is if the subview was added after our call to subviews but before the call to
1898 // sortSubviewsUsingFunction:context:. Thus we don't bother checking. Particularly because
1899 // that case should never occur anyway because that would imply a multi-threaded GUI call
1900 // which is a big no-no with Cocoa.
1902 // Subviews are ordered from back to front meaning one that is already lower will have an lower index.
1903 NSComparisonResult result = (firstI < secondI)
1904 ? NSOrderedAscending /* -1 */
1905 : (firstI > secondI)
1906 ? NSOrderedDescending /* 1 */
1907 : NSOrderedSame /* 0 */;
1912 /* The subview we are trying to Raise or Lower */
1914 /* A copy of the original array of subviews */
1915 NSArray *m_subviews;
1918 /* Causes Cocoa to raise the target view to the top of the Z-Order by telling the sort function that
1919 * the target view is always higher than every other view. When comparing two views neither of
1920 * which is the target, it returns the correct response based on the original ordering
1922 static CocoaWindowCompareFunctionResult CocoaRaiseWindowCompareFunction(id first, id second, void *ctx)
1924 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
1925 // first should be ordered higher
1926 if(first==compareContext->target())
1927 return NSOrderedDescending;
1928 // second should be ordered higher
1929 if(second==compareContext->target())
1930 return NSOrderedAscending;
1931 return compareContext->CompareUsingOriginalOrdering(first,second);
1934 void wxWidgetCocoaImpl::Raise()
1936 NSView* nsview = m_osxView;
1938 NSView *superview = [nsview superview];
1939 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
1941 [superview sortSubviewsUsingFunction:
1942 CocoaRaiseWindowCompareFunction
1943 context: &compareContext];
1947 /* Causes Cocoa to lower the target view to the bottom of the Z-Order by telling the sort function that
1948 * the target view is always lower than every other view. When comparing two views neither of
1949 * which is the target, it returns the correct response based on the original ordering
1951 static CocoaWindowCompareFunctionResult CocoaLowerWindowCompareFunction(id first, id second, void *ctx)
1953 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
1954 // first should be ordered lower
1955 if(first==compareContext->target())
1956 return NSOrderedAscending;
1957 // second should be ordered lower
1958 if(second==compareContext->target())
1959 return NSOrderedDescending;
1960 return compareContext->CompareUsingOriginalOrdering(first,second);
1963 void wxWidgetCocoaImpl::Lower()
1965 NSView* nsview = m_osxView;
1967 NSView *superview = [nsview superview];
1968 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
1970 [superview sortSubviewsUsingFunction:
1971 CocoaLowerWindowCompareFunction
1972 context: &compareContext];
1975 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
1980 // We should do something like this, but it wasn't working in 10.4.
1981 if (GetNeedsDisplay() )
1985 NSRect r = wxToNSRect( [m_osxView superview], *rect );
1986 NSSize offset = NSMakeSize((float)dx, (float)dy);
1987 [m_osxView scrollRect:r by:offset];
1991 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
1993 wxWindowMac* parent = GetWXPeer()->GetParent();
1994 // under Cocoa we might have a contentView in the wxParent to which we have to
1995 // adjust the coordinates
1996 if (parent && [m_osxView superview] != parent->GetHandle() )
1998 int cx = 0,cy = 0,cw = 0,ch = 0;
1999 if ( parent->GetPeer() )
2001 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2006 [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
2007 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
2008 [m_osxView setFrame:r];
2009 [[m_osxView superview] setNeedsDisplayInRect:r];
2012 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
2014 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
2018 // under Cocoa we might have a contentView in the wxParent to which we have to
2019 // adjust the coordinates
2020 wxWindowMac* parent = GetWXPeer()->GetParent();
2021 if (parent && [m_osxView superview] != parent->GetHandle() )
2023 int cx = 0,cy = 0,cw = 0,ch = 0;
2024 if ( parent->GetPeer() )
2026 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2033 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
2035 NSRect rect = [m_osxView frame];
2036 width = (int)rect.size.width;
2037 height = (int)rect.size.height;
2040 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
2042 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
2044 NSView* cv = [m_osxView contentView];
2046 NSRect bounds = [m_osxView bounds];
2047 NSRect rect = [cv frame];
2049 int y = (int)rect.origin.y;
2050 int x = (int)rect.origin.x;
2051 if ( ![ m_osxView isFlipped ] )
2052 y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
2055 width = (int)rect.size.width;
2056 height = (int)rect.size.height;
2061 GetSize( width, height );
2065 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
2068 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
2070 [m_osxView setNeedsDisplay:YES];
2073 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
2075 return [m_osxView needsDisplay];
2078 bool wxWidgetCocoaImpl::CanFocus() const
2080 return [m_osxView canBecomeKeyView] == YES;
2083 bool wxWidgetCocoaImpl::HasFocus() const
2085 return ( FindFocus() == m_osxView );
2088 bool wxWidgetCocoaImpl::SetFocus()
2093 // TODO remove if no issues arise: should not raise the window, only assign focus
2094 //[[m_osxView window] makeKeyAndOrderFront:nil] ;
2095 [[m_osxView window] makeFirstResponder: m_osxView] ;
2099 void wxWidgetCocoaImpl::SetDropTarget(wxDropTarget* target)
2101 [m_osxView unregisterDraggedTypes];
2103 if ( target == NULL )
2106 wxDataObject* dobj = target->GetDataObject();
2110 CFMutableArrayRef typesarray = CFArrayCreateMutable(kCFAllocatorDefault,0,&kCFTypeArrayCallBacks);
2111 dobj->AddSupportedTypes(typesarray);
2112 NSView* targetView = m_osxView;
2113 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2114 targetView = [(NSScrollView*) m_osxView documentView];
2116 [targetView registerForDraggedTypes:(NSArray*)typesarray];
2117 CFRelease(typesarray);
2121 void wxWidgetCocoaImpl::RemoveFromParent()
2123 [m_osxView removeFromSuperview];
2126 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
2128 NSView* container = parent->GetWXWidget() ;
2129 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
2130 [container addSubview:m_osxView];
2132 if( m_wxPeer->IsFrozen() )
2133 [[m_osxView window] disableFlushWindow];
2136 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
2138 NSView* targetView = m_osxView;
2139 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2140 targetView = [(NSScrollView*) m_osxView documentView];
2142 if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
2144 [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2145 green:(CGFloat) (col.Green() / 255.0)
2146 blue:(CGFloat) (col.Blue() / 255.0)
2147 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2151 bool wxWidgetCocoaImpl::SetBackgroundStyle( wxBackgroundStyle style )
2153 BOOL opaque = ( style == wxBG_STYLE_PAINT );
2155 if ( [m_osxView respondsToSelector:@selector(setOpaque:) ] )
2157 [m_osxView setOpaque: opaque];
2163 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
2165 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
2167 wxCFStringRef cf( title , encoding );
2168 [m_osxView setTitle:cf.AsNSString()];
2170 else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
2172 wxCFStringRef cf( title , encoding );
2173 [m_osxView setStringValue:cf.AsNSString()];
2178 void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
2180 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
2181 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
2182 *pt = wxFromNSPoint( to->GetWXWidget(), p );
2185 wxInt32 wxWidgetCocoaImpl::GetValue() const
2187 return [(NSControl*)m_osxView intValue];
2190 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
2192 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
2194 [m_osxView setIntValue:v];
2196 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
2198 [m_osxView setFloatValue:(double)v];
2200 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
2202 [m_osxView setDoubleValue:(double)v];
2206 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
2208 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
2210 [m_osxView setMinValue:(double)v];
2214 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
2216 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
2218 [m_osxView setMaxValue:(double)v];
2222 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
2224 if ( [m_osxView respondsToSelector:@selector(minValue)] )
2226 return (int)[m_osxView minValue];
2231 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
2233 if ( [m_osxView respondsToSelector:@selector(maxValue)] )
2235 return (int)[m_osxView maxValue];
2240 wxBitmap wxWidgetCocoaImpl::GetBitmap() const
2244 // TODO: how to create a wxBitmap from NSImage?
2246 if ( [m_osxView respondsToSelector:@selector(image:)] )
2247 bmp = [m_osxView image];
2253 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
2255 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
2258 [m_osxView setImage:bitmap.GetNSImage()];
2260 [m_osxView setImage:nil];
2262 [m_osxView setNeedsDisplay:YES];
2266 void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
2268 if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
2270 NSCellImagePosition pos;
2290 wxFAIL_MSG( "invalid image position" );
2294 [m_osxView setImagePosition:pos];
2298 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
2300 // implementation in subclass
2303 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
2305 r->x = r->y = r->width = r->height = 0;
2307 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
2309 NSRect former = [m_osxView frame];
2310 [m_osxView sizeToFit];
2311 NSRect best = [m_osxView frame];
2312 [m_osxView setFrame:former];
2313 r->width = (int)best.size.width;
2314 r->height = (int)best.size.height;
2318 bool wxWidgetCocoaImpl::IsEnabled() const
2320 NSView* targetView = m_osxView;
2321 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2322 targetView = [(NSScrollView*) m_osxView documentView];
2324 if ( [targetView respondsToSelector:@selector(isEnabled) ] )
2325 return [targetView isEnabled];
2329 void wxWidgetCocoaImpl::Enable( bool enable )
2331 NSView* targetView = m_osxView;
2332 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2333 targetView = [(NSScrollView*) m_osxView documentView];
2335 if ( [targetView respondsToSelector:@selector(setEnabled:) ] )
2336 [targetView setEnabled:enable];
2339 void wxWidgetCocoaImpl::PulseGauge()
2343 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
2347 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
2349 NSControlSize size = NSRegularControlSize;
2353 case wxWINDOW_VARIANT_NORMAL :
2354 size = NSRegularControlSize;
2357 case wxWINDOW_VARIANT_SMALL :
2358 size = NSSmallControlSize;
2361 case wxWINDOW_VARIANT_MINI :
2362 size = NSMiniControlSize;
2365 case wxWINDOW_VARIANT_LARGE :
2366 size = NSRegularControlSize;
2370 wxFAIL_MSG(wxT("unexpected window variant"));
2373 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
2374 [m_osxView setControlSize:size];
2375 else if ([m_osxView respondsToSelector:@selector(cell)])
2377 id cell = [(id)m_osxView cell];
2378 if ([cell respondsToSelector:@selector(setControlSize:)])
2379 [cell setControlSize:size];
2382 // we need to propagate this to inner views as well
2383 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2385 NSView* targetView = [(NSScrollView*) m_osxView documentView];
2387 if ( [targetView respondsToSelector:@selector(setControlSize:)] )
2388 [targetView setControlSize:size];
2389 else if ([targetView respondsToSelector:@selector(cell)])
2391 id cell = [(id)targetView cell];
2392 if ([cell respondsToSelector:@selector(setControlSize:)])
2393 [cell setControlSize:size];
2398 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&col, long, bool)
2400 NSView* targetView = m_osxView;
2401 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2402 targetView = [(NSScrollView*) m_osxView documentView];
2404 if ([targetView respondsToSelector:@selector(setFont:)])
2405 [targetView setFont: font.OSXGetNSFont()];
2406 if ([targetView respondsToSelector:@selector(setTextColor:)])
2407 [targetView setTextColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2408 green:(CGFloat) (col.Green() / 255.0)
2409 blue:(CGFloat) (col.Blue() / 255.0)
2410 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2413 void wxWidgetCocoaImpl::SetToolTip(wxToolTip* tooltip)
2417 wxCFStringRef cf( tooltip->GetTip() , m_wxPeer->GetFont().GetEncoding() );
2418 [m_osxView setToolTip: cf.AsNSString()];
2422 [m_osxView setToolTip:nil];
2426 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
2428 WXWidget c = control ? control : (WXWidget) m_osxView;
2429 wxWidgetImpl::Associate( c, this ) ;
2430 if ([c respondsToSelector:@selector(setAction:)])
2433 [c setAction: @selector(controlAction:)];
2434 if ([c respondsToSelector:@selector(setDoubleAction:)])
2436 [c setDoubleAction: @selector(controlDoubleAction:)];
2440 NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingCursorUpdate|NSTrackingMouseMoved|NSTrackingActiveAlways|NSTrackingInVisibleRect;
2441 NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: NSZeroRect options: options owner: m_osxView userInfo: nil];
2442 [m_osxView addTrackingArea: area];
2446 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
2448 wxKeyEvent wxevent(wxEVT_CHAR);
2449 SetupKeyEvent( wxevent, event, text );
2451 return GetWXPeer()->OSXHandleKeyEvent(wxevent);
2454 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
2456 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
2457 SetupKeyEvent( wxevent, event );
2459 // Generate wxEVT_CHAR_HOOK before sending any other events but only when
2460 // the key is pressed, not when it's released (the type of wxevent is
2461 // changed by SetupKeyEvent() so it can be wxEVT_KEY_UP too by now).
2462 if ( wxevent.GetEventType() == wxEVT_KEY_DOWN )
2464 wxKeyEvent eventHook(wxEVT_CHAR_HOOK, wxevent);
2465 if ( GetWXPeer()->OSXHandleKeyEvent(eventHook)
2466 && !eventHook.IsNextEventAllowed() )
2470 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
2472 // this will fire higher level events, like insertText, to help
2473 // us handle EVT_CHAR, etc.
2477 if ( [event type] == NSKeyDown)
2479 long keycode = wxOSXTranslateCocoaKey( event, wxEVT_CHAR );
2481 if ( (keycode > 0 && keycode < WXK_SPACE) || keycode == WXK_DELETE || keycode >= WXK_START )
2483 // eventually we could setup a doCommandBySelector catcher and retransform this into the wx key chars
2484 wxKeyEvent wxevent2(wxevent) ;
2485 wxevent2.SetEventType(wxEVT_CHAR);
2486 SetupKeyEvent( wxevent2, event );
2487 wxevent2.m_keyCode = keycode;
2488 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2490 else if (wxevent.CmdDown())
2492 wxKeyEvent wxevent2(wxevent) ;
2493 wxevent2.SetEventType(wxEVT_CHAR);
2494 SetupKeyEvent( wxevent2, event );
2495 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2499 if ( IsUserPane() && !wxevent.CmdDown() )
2501 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2502 [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
2504 [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
2514 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
2516 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
2517 SetupMouseEvent(wxevent , event) ;
2518 return GetWXPeer()->HandleWindowEvent(wxevent);
2521 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
2523 wxWindow* thisWindow = GetWXPeer();
2524 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
2526 thisWindow->MacInvalidateBorders();
2529 if ( receivedFocus )
2531 wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
2532 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
2533 thisWindow->HandleWindowEvent(eventFocus);
2536 if ( thisWindow->GetCaret() )
2537 thisWindow->GetCaret()->OnSetFocus();
2540 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
2541 event.SetEventObject(thisWindow);
2543 event.SetWindow(otherWindow->GetWXPeer());
2544 thisWindow->HandleWindowEvent(event) ;
2546 else // !receivedFocus
2549 if ( thisWindow->GetCaret() )
2550 thisWindow->GetCaret()->OnKillFocus();
2553 wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
2555 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
2556 event.SetEventObject(thisWindow);
2558 event.SetWindow(otherWindow->GetWXPeer());
2559 thisWindow->HandleWindowEvent(event) ;
2563 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
2567 NSPoint location = [NSEvent mouseLocation];
2568 location = [[m_osxView window] convertScreenToBase:location];
2569 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
2571 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
2573 [(NSCursor*)cursor.GetHCURSOR() set];
2578 void wxWidgetCocoaImpl::CaptureMouse()
2580 // TODO remove if we don't get into problems with cursor settings
2581 // [[m_osxView window] disableCursorRects];
2584 void wxWidgetCocoaImpl::ReleaseMouse()
2586 // TODO remove if we don't get into problems with cursor settings
2587 // [[m_osxView window] enableCursorRects];
2590 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
2592 m_isFlipped = flipped;
2595 void wxWidgetCocoaImpl::SetDrawingEnabled(bool enabled)
2599 [[m_osxView window] enableFlushWindow];
2600 [m_osxView setNeedsDisplay:YES];
2604 [[m_osxView window] disableFlushWindow];
2611 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
2612 wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
2613 long WXUNUSED(style), long WXUNUSED(extraStyle))
2615 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
2616 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
2618 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v, false, true );
2622 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
2624 NSWindow* tlw = now->GetWXWindow();
2626 wxWidgetCocoaImpl* c = NULL;
2627 if ( now->IsNativeWindowWrapper() )
2629 NSView* cv = [tlw contentView];
2630 c = new wxWidgetCocoaImpl( now, cv, true );
2631 // increase ref count, because the impl destructor will decrement it again
2633 if ( !now->IsShown() )
2639 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2640 c = new wxWidgetCocoaImpl( now, v, true );
2641 c->InstallEventHandler();
2642 [tlw setContentView:v];