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;
95 NSTrackingArea* _trackingArea;
98 - (void) updateTrackingArea;
99 - (NSTrackingArea*) trackingArea;
102 @interface NSView(PossibleMethods)
103 - (void)setTitle:(NSString *)aString;
104 - (void)setStringValue:(NSString *)aString;
105 - (void)setIntValue:(int)anInt;
106 - (void)setFloatValue:(float)aFloat;
107 - (void)setDoubleValue:(double)aDouble;
111 - (void)setMinValue:(double)aDouble;
112 - (void)setMaxValue:(double)aDouble;
117 - (void)setEnabled:(BOOL)flag;
119 - (void)setImage:(NSImage *)image;
120 - (void)setControlSize:(NSControlSize)size;
122 - (void)setFont:(NSFont *)fontObject;
126 - (void)setTarget:(id)anObject;
127 - (void)setAction:(SEL)aSelector;
128 - (void)setDoubleAction:(SEL)aSelector;
129 - (void)setBackgroundColor:(NSColor*)aColor;
130 - (void)setOpaque:(BOOL)opaque;
131 - (void)setTextColor:(NSColor *)color;
132 - (void)setImagePosition:(NSCellImagePosition)aPosition;
135 // The following code is a combination of the code listed here:
136 // http://lists.apple.com/archives/cocoa-dev/2008/Apr/msg01582.html
137 // (which can't be used because KLGetCurrentKeyboardLayout etc aren't 64-bit)
138 // and the code here:
139 // http://inquisitivecocoa.com/category/objective-c/
140 @interface NSEvent (OsGuiUtilsAdditions)
141 - (NSString*) charactersIgnoringModifiersIncludingShift;
144 @implementation NSEvent (OsGuiUtilsAdditions)
145 - (NSString*) charactersIgnoringModifiersIncludingShift {
146 // First try -charactersIgnoringModifiers and look for keys which UCKeyTranslate translates
147 // differently than AppKit.
148 NSString* c = [self charactersIgnoringModifiers];
149 if ([c length] == 1) {
150 unichar codepoint = [c characterAtIndex:0];
151 if ((codepoint >= 0xF700 && codepoint <= 0xF8FF) || codepoint == 0x7F) {
155 // This is not a "special" key, so ask UCKeyTranslate to give us the character with no
156 // modifiers attached. Actually, that's not quite accurate; we attach the Command modifier
157 // which hints the OS to use Latin characters where possible, which is generally what we want.
158 NSString* result = @"";
159 TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
160 CFDataRef uchr = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
161 CFRelease(currentKeyboard);
163 // this can happen for some non-U.S. input methods (eg. Romaji or Hiragana)
166 const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout*)CFDataGetBytePtr(uchr);
167 if (keyboardLayout) {
168 UInt32 deadKeyState = 0;
169 UniCharCount maxStringLength = 255;
170 UniCharCount actualStringLength = 0;
171 UniChar unicodeString[maxStringLength];
173 OSStatus status = UCKeyTranslate(keyboardLayout,
176 cmdKey >> 8, // force the Command key to "on"
178 kUCKeyTranslateNoDeadKeysMask,
185 result = [NSString stringWithCharacters:unicodeString length:(NSInteger)actualStringLength];
191 long wxOSXTranslateCocoaKey( NSEvent* event, int eventType )
195 if ([event type] != NSFlagsChanged)
197 NSString* s = [event charactersIgnoringModifiersIncludingShift];
198 // backspace char reports as delete w/modifiers for some reason
201 if ( eventType == wxEVT_CHAR && ([event modifierFlags] & NSControlKeyMask) && ( [s characterAtIndex:0] >= 'a' && [s characterAtIndex:0] <= 'z' ) )
203 retval = WXK_CONTROL_A + ([s characterAtIndex:0] - 'a');
207 switch ( [s characterAtIndex:0] )
214 case NSUpArrowFunctionKey :
217 case NSDownArrowFunctionKey :
220 case NSLeftArrowFunctionKey :
223 case NSRightArrowFunctionKey :
226 case NSInsertFunctionKey :
229 case NSDeleteFunctionKey :
232 case NSHomeFunctionKey :
235 // case NSBeginFunctionKey :
236 // retval = WXK_BEGIN;
238 case NSEndFunctionKey :
241 case NSPageUpFunctionKey :
244 case NSPageDownFunctionKey :
245 retval = WXK_PAGEDOWN;
247 case NSHelpFunctionKey :
251 int intchar = [s characterAtIndex: 0];
252 if ( intchar >= NSF1FunctionKey && intchar <= NSF24FunctionKey )
253 retval = WXK_F1 + (intchar - NSF1FunctionKey );
254 else if ( intchar > 0 && intchar < 32 )
262 // Some keys don't seem to have constants. The code mimics the approach
263 // taken by WebKit. See:
264 // http://trac.webkit.org/browser/trunk/WebCore/platform/mac/KeyEventMac.mm
265 switch( [event keyCode] )
270 retval = WXK_CONTROL;
274 retval = WXK_CAPITAL;
277 case 56: // Left Shift
278 case 60: // Right Shift
283 case 61: // Right Alt
287 case 59: // Left Ctrl
288 case 62: // Right Ctrl
289 retval = WXK_RAW_CONTROL;
301 retval = WXK_NUMPAD_DIVIDE;
304 retval = WXK_NUMPAD_MULTIPLY;
307 retval = WXK_NUMPAD_SUBTRACT;
310 retval = WXK_NUMPAD_ADD;
313 retval = WXK_NUMPAD_ENTER;
316 retval = WXK_NUMPAD_DECIMAL;
319 retval = WXK_NUMPAD0;
322 retval = WXK_NUMPAD1;
325 retval = WXK_NUMPAD2;
328 retval = WXK_NUMPAD3;
331 retval = WXK_NUMPAD4;
334 retval = WXK_NUMPAD5;
337 retval = WXK_NUMPAD6;
340 retval = WXK_NUMPAD7;
343 retval = WXK_NUMPAD8;
346 retval = WXK_NUMPAD9;
349 //retval = [event keyCode];
355 void wxWidgetCocoaImpl::SetupKeyEvent(wxKeyEvent &wxevent , NSEvent * nsEvent, NSString* charString)
357 UInt32 modifiers = [nsEvent modifierFlags] ;
358 int eventType = [nsEvent type];
360 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
361 wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
362 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
363 wxevent.m_controlDown = modifiers & NSCommandKeyMask;
365 wxevent.m_rawCode = [nsEvent keyCode];
366 wxevent.m_rawFlags = modifiers;
368 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
371 if ( eventType != NSFlagsChanged )
373 NSString* nschars = [[nsEvent charactersIgnoringModifiersIncludingShift] uppercaseString];
376 // if charString is set, it did not come from key up / key down
377 wxevent.SetEventType( wxEVT_CHAR );
378 chars = wxCFStringRef::AsString(charString);
382 chars = wxCFStringRef::AsString(nschars);
386 int aunichar = chars.Length() > 0 ? chars[0] : 0;
389 if (wxevent.GetEventType() != wxEVT_CHAR)
391 keyval = wxOSXTranslateCocoaKey(nsEvent, wxevent.GetEventType()) ;
395 wxevent.SetEventType( wxEVT_KEY_DOWN ) ;
398 wxevent.SetEventType( wxEVT_KEY_UP ) ;
400 case NSFlagsChanged :
404 wxevent.SetEventType( wxevent.m_controlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
407 wxevent.SetEventType( wxevent.m_shiftDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
410 wxevent.SetEventType( wxevent.m_altDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
412 case WXK_RAW_CONTROL:
413 wxevent.SetEventType( wxevent.m_rawControlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
424 if ( wxevent.GetEventType() == wxEVT_KEY_UP || wxevent.GetEventType() == wxEVT_KEY_DOWN )
425 keyval = wxToupper( aunichar ) ;
431 // OS X generates events with key codes in Unicode private use area for
432 // unprintable symbols such as cursor arrows (WXK_UP is mapped to U+F700)
433 // and function keys (WXK_F2 is U+F705). We don't want to use them as the
434 // result of wxKeyEvent::GetUnicodeKey() however as it's supposed to return
435 // WXK_NONE for "non characters" so explicitly exclude them.
437 // We only exclude the private use area inside the Basic Multilingual Plane
438 // as key codes beyond it don't seem to be currently used.
439 if ( !(aunichar >= 0xe000 && aunichar < 0xf900) )
440 wxevent.m_uniChar = aunichar;
442 wxevent.m_keyCode = keyval;
444 wxWindowMac* peer = GetWXPeer();
447 wxevent.SetEventObject(peer);
448 wxevent.SetId(peer->GetId()) ;
452 UInt32 g_lastButton = 0 ;
453 bool g_lastButtonWasFakeRight = false ;
455 // better scroll wheel support
456 // see http://lists.apple.com/archives/cocoa-dev/2007/Feb/msg00050.html
458 @interface NSEvent (DeviceDelta)
459 - (CGFloat)deviceDeltaX;
460 - (CGFloat)deviceDeltaY;
463 void wxWidgetCocoaImpl::SetupMouseEvent( wxMouseEvent &wxevent , NSEvent * nsEvent )
465 int eventType = [nsEvent type];
466 UInt32 modifiers = [nsEvent modifierFlags] ;
468 NSPoint locationInWindow = [nsEvent locationInWindow];
470 // adjust coordinates for the window of the target view
471 if ( [nsEvent window] != [m_osxView window] )
473 if ( [nsEvent window] != nil )
474 locationInWindow = [[nsEvent window] convertBaseToScreen:locationInWindow];
476 if ( [m_osxView window] != nil )
477 locationInWindow = [[m_osxView window] convertScreenToBase:locationInWindow];
480 NSPoint locationInView = [m_osxView convertPoint:locationInWindow fromView:nil];
481 wxPoint locationInViewWX = wxFromNSPoint( m_osxView, locationInView );
483 // these parameters are not given for all events
484 UInt32 button = [nsEvent buttonNumber];
485 UInt32 clickCount = 0;
487 wxevent.m_x = locationInViewWX.x;
488 wxevent.m_y = locationInViewWX.y;
489 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
490 wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
491 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
492 wxevent.m_controlDown = modifiers & NSCommandKeyMask;
493 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
495 UInt32 mouseChord = 0;
499 case NSLeftMouseDown :
500 case NSLeftMouseDragged :
503 case NSRightMouseDown :
504 case NSRightMouseDragged :
507 case NSOtherMouseDown :
508 case NSOtherMouseDragged :
513 // a control click is interpreted as a right click
514 bool thisButtonIsFakeRight = false ;
515 if ( button == 0 && (modifiers & NSControlKeyMask) )
518 thisButtonIsFakeRight = true ;
521 // otherwise we report double clicks by connecting a left click with a ctrl-left click
522 if ( clickCount > 1 && button != g_lastButton )
525 // we must make sure that our synthetic 'right' button corresponds in
526 // mouse down, moved and mouse up, and does not deliver a right down and left up
529 case NSLeftMouseDown :
530 case NSRightMouseDown :
531 case NSOtherMouseDown :
532 g_lastButton = button ;
533 g_lastButtonWasFakeRight = thisButtonIsFakeRight ;
540 g_lastButtonWasFakeRight = false ;
542 else if ( g_lastButton == 1 && g_lastButtonWasFakeRight )
543 button = g_lastButton ;
545 // Adjust the chord mask to remove the primary button and add the
546 // secondary button. It is possible that the secondary button is
547 // already pressed, e.g. on a mouse connected to a laptop, but this
548 // possibility is ignored here:
549 if( thisButtonIsFakeRight && ( mouseChord & 1U ) )
550 mouseChord = ((mouseChord & ~1U) | 2U);
553 wxevent.m_leftDown = true ;
555 wxevent.m_rightDown = true ;
557 wxevent.m_middleDown = true ;
559 // translate into wx types
562 case NSLeftMouseDown :
563 case NSRightMouseDown :
564 case NSOtherMouseDown :
565 clickCount = [nsEvent clickCount];
569 wxevent.SetEventType( clickCount > 1 ? wxEVT_LEFT_DCLICK : wxEVT_LEFT_DOWN ) ;
573 wxevent.SetEventType( clickCount > 1 ? wxEVT_RIGHT_DCLICK : wxEVT_RIGHT_DOWN ) ;
577 wxevent.SetEventType( clickCount > 1 ? wxEVT_MIDDLE_DCLICK : wxEVT_MIDDLE_DOWN ) ;
586 case NSRightMouseUp :
587 case NSOtherMouseUp :
588 clickCount = [nsEvent clickCount];
592 wxevent.SetEventType( wxEVT_LEFT_UP ) ;
596 wxevent.SetEventType( wxEVT_RIGHT_UP ) ;
600 wxevent.SetEventType( wxEVT_MIDDLE_UP ) ;
613 wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ;
615 // see http://developer.apple.com/qa/qa2005/qa1453.html
616 // for more details on why we have to look for the exact type
618 const EventRef cEvent = (EventRef) [nsEvent eventRef];
619 bool isMouseScrollEvent = false;
621 isMouseScrollEvent = ::GetEventKind(cEvent) == kEventMouseScroll;
623 if ( isMouseScrollEvent )
625 deltaX = [nsEvent deviceDeltaX];
626 deltaY = [nsEvent deviceDeltaY];
630 deltaX = ([nsEvent deltaX] * 10);
631 deltaY = ([nsEvent deltaY] * 10);
634 wxevent.m_wheelDelta = 10;
635 wxevent.m_linesPerAction = 1;
637 if ( fabs(deltaX) > fabs(deltaY) )
639 wxevent.m_wheelAxis = 1;
640 wxevent.m_wheelRotation = (int)deltaX;
644 wxevent.m_wheelRotation = (int)deltaY;
650 case NSMouseEntered :
651 wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
654 wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
656 case NSLeftMouseDragged :
657 case NSRightMouseDragged :
658 case NSOtherMouseDragged :
660 wxevent.SetEventType( wxEVT_MOTION ) ;
666 wxevent.m_clickCount = clickCount;
667 wxWindowMac* peer = GetWXPeer();
670 wxevent.SetEventObject(peer);
671 wxevent.SetId(peer->GetId()) ;
675 @implementation wxNSView
679 static BOOL initialized = NO;
683 wxOSXCocoaClassAddWXMethods( self );
687 - (void) updateTrackingArea
691 [self removeTrackingArea: _trackingArea];
692 [_trackingArea release];
695 NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingMouseMoved|NSTrackingActiveAlways;
697 NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: [self bounds] options: options owner: self userInfo: nil];
698 [self addTrackingArea: area];
700 _trackingArea = area;
703 - (NSTrackingArea*) trackingArea
705 return _trackingArea;
708 /* idea taken from webkit sources: overwrite the methods that (private) NSToolTipManager will use to attach its tracking rectangle
709 * then when changing the tooltip send fake view-exit and view-enter methods which will lead to a tooltip refresh
713 - (void)_sendToolTipMouseExited
715 // Nothing matters except window, trackingNumber, and userData.
716 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
717 location:NSMakePoint(0, 0)
720 windowNumber:[[self window] windowNumber]
723 trackingNumber:_lastToolTipTrackTag
724 userData:_lastUserData];
725 [_lastToolTipOwner mouseExited:fakeEvent];
728 - (void)_sendToolTipMouseEntered
730 // Nothing matters except window, trackingNumber, and userData.
731 NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
732 location:NSMakePoint(0, 0)
735 windowNumber:[[self window] windowNumber]
738 trackingNumber:_lastToolTipTrackTag
739 userData:_lastUserData];
740 [_lastToolTipOwner mouseEntered:fakeEvent];
743 - (void)setToolTip:(NSString *)string;
749 [self _sendToolTipMouseExited];
752 [super setToolTip:string];
754 [self _sendToolTipMouseEntered];
760 [self _sendToolTipMouseExited];
761 [super setToolTip:nil];
767 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
769 NSTrackingRectTag tag = [super addTrackingRect:rect owner:owner userData:data assumeInside:assumeInside];
772 _lastUserData = data;
773 _lastToolTipOwner = owner;
774 _lastToolTipTrackTag = tag;
779 - (void)removeTrackingRect:(NSTrackingRectTag)tag
781 if (tag == _lastToolTipTrackTag)
783 _lastUserData = NULL;
784 _lastToolTipOwner = nil;
785 _lastToolTipTrackTag = 0;
787 [super removeTrackingRect:tag];
795 #if wxUSE_DRAG_AND_DROP
797 // see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
798 // for details on the NSPasteboard -> PasteboardRef conversion
800 NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
802 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
804 return NSDragOperationNone;
806 return impl->draggingEntered(sender, self, _cmd);
809 void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
811 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
815 return impl->draggingExited(sender, self, _cmd);
818 NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
820 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
822 return NSDragOperationNone;
824 return impl->draggingUpdated(sender, self, _cmd);
827 BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
829 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
831 return NSDragOperationNone;
833 return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
838 void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
840 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
844 impl->mouseEvent(event, self, _cmd);
847 BOOL wxOSX_acceptsFirstMouse(NSView* WXUNUSED(self), SEL WXUNUSED(_cmd), NSEvent *WXUNUSED(event))
849 // This is needed to support click through, otherwise the first click on a window
850 // will not do anything unless it is the active window already.
854 void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
856 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
860 impl->keyEvent(event, self, _cmd);
863 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
865 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
869 impl->insertText(text, self, _cmd);
872 BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
874 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
878 return impl->performKeyEquivalent(event, self, _cmd);
881 BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
883 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
887 return impl->acceptsFirstResponder(self, _cmd);
890 BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
892 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
896 return impl->becomeFirstResponder(self, _cmd);
899 BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
901 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
905 return impl->resignFirstResponder(self, _cmd);
908 void wxOSX_resetCursorRects(NSView* self, SEL _cmd)
910 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
914 impl->resetCursorRects(self, _cmd);
917 BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
919 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
923 return impl->isFlipped(self, _cmd) ? YES:NO;
926 typedef void (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
928 void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
930 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
935 // OS X starts a NSUIHeartBeatThread for animating the default button in a
936 // dialog. This causes a drawRect of the active dialog from outside the
937 // main UI thread. This causes an occasional crash since the wx drawing
938 // objects (like wxPen) are not thread safe.
940 // Notice that NSUIHeartBeatThread seems to be undocumented and doing
941 // [NSWindow setAllowsConcurrentViewDrawing:NO] does not affect it.
942 if ( !wxThread::IsMain() )
944 if ( impl->IsUserPane() )
946 wxWindow* win = impl->GetWXPeer();
947 if ( win->UseBgCol() )
950 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
951 CGContextSaveGState( context );
953 CGContextSetFillColorWithColor( context, win->GetBackgroundColour().GetCGColor());
954 CGRect r = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
955 CGContextFillRect( context, r );
957 CGContextRestoreGState( context );
962 // just call the superclass handler, we don't need any custom wx drawing
963 // here and it seems to work fine:
964 wxOSX_DrawRectHandlerPtr
965 superimpl = (wxOSX_DrawRectHandlerPtr)
966 [[self superclass] instanceMethodForSelector:_cmd];
967 superimpl(self, _cmd, rect);
972 #endif // wxUSE_THREADS
974 return impl->drawRect(&rect, self, _cmd);
977 void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
979 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
983 impl->controlAction(self, _cmd, sender);
986 void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
988 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
992 impl->controlDoubleAction(self, _cmd, sender);
995 unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
997 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
998 NSPasteboard *pboard = [sender draggingPasteboard];
999 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1001 wxWindow* wxpeer = GetWXPeer();
1002 if ( wxpeer == NULL )
1003 return NSDragOperationNone;
1005 wxDropTarget* target = wxpeer->GetDropTarget();
1006 if ( target == NULL )
1007 return NSDragOperationNone;
1009 wxDragResult result = wxDragNone;
1010 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1011 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1013 if ( sourceDragMask & NSDragOperationLink )
1014 result = wxDragLink;
1015 else if ( sourceDragMask & NSDragOperationCopy )
1016 result = wxDragCopy;
1017 else if ( sourceDragMask & NSDragOperationMove )
1018 result = wxDragMove;
1020 PasteboardRef pboardRef;
1021 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1022 target->SetCurrentDragPasteboard(pboardRef);
1023 result = target->OnEnter(pt.x, pt.y, result);
1024 CFRelease(pboardRef);
1026 NSDragOperation nsresult = NSDragOperationNone;
1030 nsresult = NSDragOperationLink;
1032 nsresult = NSDragOperationMove;
1034 nsresult = NSDragOperationCopy;
1041 void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1043 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1044 NSPasteboard *pboard = [sender draggingPasteboard];
1046 wxWindow* wxpeer = GetWXPeer();
1047 if ( wxpeer == NULL )
1050 wxDropTarget* target = wxpeer->GetDropTarget();
1051 if ( target == NULL )
1054 PasteboardRef pboardRef;
1055 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1056 target->SetCurrentDragPasteboard(pboardRef);
1058 CFRelease(pboardRef);
1061 unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1063 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1064 NSPasteboard *pboard = [sender draggingPasteboard];
1065 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1067 wxWindow* wxpeer = GetWXPeer();
1068 if ( wxpeer == NULL )
1069 return NSDragOperationNone;
1071 wxDropTarget* target = wxpeer->GetDropTarget();
1072 if ( target == NULL )
1073 return NSDragOperationNone;
1075 wxDragResult result = wxDragNone;
1076 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1077 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1079 if ( sourceDragMask & NSDragOperationLink )
1080 result = wxDragLink;
1081 else if ( sourceDragMask & NSDragOperationCopy )
1082 result = wxDragCopy;
1083 else if ( sourceDragMask & NSDragOperationMove )
1084 result = wxDragMove;
1086 PasteboardRef pboardRef;
1087 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1088 target->SetCurrentDragPasteboard(pboardRef);
1089 result = target->OnDragOver(pt.x, pt.y, result);
1090 CFRelease(pboardRef);
1092 NSDragOperation nsresult = NSDragOperationNone;
1096 nsresult = NSDragOperationLink;
1098 nsresult = NSDragOperationMove;
1100 nsresult = NSDragOperationCopy;
1107 bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1109 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1111 NSPasteboard *pboard = [sender draggingPasteboard];
1112 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1114 wxWindow* wxpeer = GetWXPeer();
1115 wxDropTarget* target = wxpeer->GetDropTarget();
1116 wxDragResult result = wxDragNone;
1117 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1118 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1120 if ( sourceDragMask & NSDragOperationLink )
1121 result = wxDragLink;
1122 else if ( sourceDragMask & NSDragOperationCopy )
1123 result = wxDragCopy;
1124 else if ( sourceDragMask & NSDragOperationMove )
1125 result = wxDragMove;
1127 PasteboardRef pboardRef;
1128 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1129 target->SetCurrentDragPasteboard(pboardRef);
1131 if (target->OnDrop(pt.x, pt.y))
1132 result = target->OnData(pt.x, pt.y, result);
1134 CFRelease(pboardRef);
1136 return result != wxDragNone;
1139 typedef void (*wxOSX_TextEventHandlerPtr)(NSView* self, SEL _cmd, NSString *event);
1140 typedef void (*wxOSX_EventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
1141 typedef BOOL (*wxOSX_PerformKeyEventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
1142 typedef BOOL (*wxOSX_FocusHandlerPtr)(NSView* self, SEL _cmd);
1143 typedef BOOL (*wxOSX_ResetCursorRectsHandlerPtr)(NSView* self, SEL _cmd);
1145 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1147 if ( !DoHandleMouseEvent(event) )
1149 // for plain NSView mouse events would propagate to parents otherwise
1152 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1153 superimpl(slf, (SEL)_cmd, event);
1155 // super of built-ins keeps the mouse up, as wx expects this event, we have to synthesize it
1157 if ( [ event type] == NSLeftMouseDown )
1159 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
1160 SetupMouseEvent(wxevent , event) ;
1161 wxevent.SetEventType(wxEVT_LEFT_UP);
1163 GetWXPeer()->HandleWindowEvent(wxevent);
1169 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1171 if ( [event type] == NSKeyDown )
1173 // there are key equivalents that are not command-combos and therefore not handled by cocoa automatically,
1174 // therefore we call the menubar directly here, exit if the menu is handling the shortcut
1175 if ( [[[NSApplication sharedApplication] mainMenu] performKeyEquivalent:event] )
1178 m_lastKeyDownEvent = event;
1181 if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
1183 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1184 superimpl(slf, (SEL)_cmd, event);
1186 m_lastKeyDownEvent = NULL;
1189 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
1191 if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
1193 wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1194 superimpl(slf, (SEL)_cmd, text);
1199 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
1201 bool handled = false;
1203 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1204 SetupKeyEvent( wxevent, event );
1206 // because performKeyEquivalent is going up the entire view hierarchy, we don't have to
1207 // walk up the ancestors ourselves but let cocoa do it
1209 int command = m_wxPeer->GetAcceleratorTable()->GetCommand( wxevent );
1212 wxEvtHandler * const handler = m_wxPeer->GetEventHandler();
1214 wxCommandEvent command_event( wxEVT_COMMAND_MENU_SELECTED, command );
1215 command_event.SetEventObject( wxevent.GetEventObject() );
1216 handled = handler->ProcessEvent( command_event );
1220 // accelerators can also be used with buttons, try them too
1221 command_event.SetEventType(wxEVT_COMMAND_BUTTON_CLICKED);
1222 handled = handler->ProcessEvent( command_event );
1228 wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1229 return superimpl(slf, (SEL)_cmd, event);
1234 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
1237 return m_wxPeer->AcceptsFocus();
1240 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1241 return superimpl(slf, (SEL)_cmd);
1245 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
1247 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1248 // get the current focus before running becomeFirstResponder
1249 NSView* otherView = FindFocus();
1251 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1252 BOOL r = superimpl(slf, (SEL)_cmd);
1255 DoNotifyFocusEvent( true, otherWindow );
1261 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
1263 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1264 BOOL r = superimpl(slf, (SEL)_cmd);
1265 // get the current focus after running resignFirstResponder
1266 // note that this value isn't reliable, it might return the same view that
1268 NSView* otherView = FindFocus();
1269 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1271 // It doesn't make sense to notify about the loss of focus if we're not
1272 // really losing it and the window which has just gained focus is the same
1273 // one as this window itself. Of course, this should never happen in the
1274 // first place but somehow it does in wxGrid code and without this check we
1275 // enter into an infinite recursion, see #12267.
1276 if ( otherWindow == this )
1279 // NSTextViews have an editor as true responder, therefore the might get the
1280 // resign notification if their editor takes over, don't trigger any event then
1281 if ( r && !m_hasEditor)
1283 DoNotifyFocusEvent( false, otherWindow );
1288 void wxWidgetCocoaImpl::resetCursorRects(WXWidget slf, void *_cmd)
1290 wxWindow* wxpeer = GetWXPeer();
1293 NSCursor *cursor = (NSCursor*)wxpeer->GetCursor().GetHCURSOR();
1296 wxOSX_ResetCursorRectsHandlerPtr superimpl = (wxOSX_ResetCursorRectsHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1297 superimpl(slf, (SEL)_cmd);
1301 [slf addCursorRect: [slf bounds]
1307 bool wxWidgetCocoaImpl::isFlipped(WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1313 #define OSX_DEBUG_DRAWING 0
1315 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
1317 // preparing the update region
1320 const NSRect *rects;
1323 [slf getRectsBeingDrawn:&rects count:&count];
1324 for ( int i = 0 ; i < count ; ++i )
1326 updateRgn.Union(wxFromNSRect(slf, rects[i]));
1329 wxWindow* wxpeer = GetWXPeer();
1331 if ( wxpeer->MacGetLeftBorderSize() != 0 || wxpeer->MacGetTopBorderSize() != 0 )
1333 // as this update region is in native window locals we must adapt it to wx window local
1334 updateRgn.Offset( wxpeer->MacGetLeftBorderSize() , wxpeer->MacGetTopBorderSize() );
1337 // Restrict the update region to the shape of the window, if any, and also
1338 // remember the region that we need to clear later.
1339 wxNonOwnedWindow* const tlwParent = wxpeer->MacGetTopLevelWindow();
1340 const bool isTopLevel = tlwParent == wxpeer;
1342 if ( tlwParent->GetWindowStyle() & wxFRAME_SHAPED )
1345 clearRgn = updateRgn;
1347 int xoffset = 0, yoffset = 0;
1348 wxRegion rgn = tlwParent->GetShape();
1349 wxpeer->MacRootWindowToWindow( &xoffset, &yoffset );
1350 rgn.Offset( xoffset, yoffset );
1351 updateRgn.Intersect(rgn);
1355 // Exclude the window shape from the region to be cleared below.
1356 rgn.Xor(wxpeer->GetSize());
1357 clearRgn.Intersect(rgn);
1361 wxpeer->GetUpdateRegion() = updateRgn;
1363 // setting up the drawing context
1365 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1366 CGContextSaveGState( context );
1368 #if OSX_DEBUG_DRAWING
1369 CGContextBeginPath( context );
1370 CGContextMoveToPoint(context, 0, 0);
1371 NSRect bounds = [slf bounds];
1372 CGContextAddLineToPoint(context, 10, 0);
1373 CGContextMoveToPoint(context, 0, 0);
1374 CGContextAddLineToPoint(context, 0, 10);
1375 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1376 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1377 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1378 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1379 CGContextClosePath( context );
1380 CGContextStrokePath(context);
1385 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1386 CGContextScaleCTM( context, 1, -1 );
1389 wxpeer->MacSetCGContextRef( context );
1391 bool handled = wxpeer->MacDoRedraw( 0 );
1392 CGContextRestoreGState( context );
1394 CGContextSaveGState( context );
1398 SEL _cmd = @selector(drawRect:);
1399 wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1400 superimpl(slf, _cmd, *(NSRect*)rect);
1401 CGContextRestoreGState( context );
1402 CGContextSaveGState( context );
1404 // as we called restore above, we have to flip again if necessary
1407 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1408 CGContextScaleCTM( context, 1, -1 );
1413 // We also need to explicitly draw the part of the top level window
1414 // outside of its region with transparent colour to ensure that it is
1415 // really transparent.
1416 if ( clearRgn.IsOk() )
1418 wxMacCGContextStateSaver saveState(context);
1419 wxWindowDC dc(wxpeer);
1420 dc.SetBackground(wxBrush(wxTransparentColour));
1421 dc.SetDeviceClippingRegion(clearRgn);
1425 #if wxUSE_GRAPHICS_CONTEXT
1426 // If the window shape is defined by a path, stroke the path to show
1427 // the window border.
1428 const wxGraphicsPath& path = tlwParent->GetShapePath();
1429 if ( !path.IsNull() )
1431 CGContextSetLineWidth(context, 1);
1432 CGContextSetStrokeColorWithColor(context, wxLIGHT_GREY->GetCGColor());
1433 CGContextAddPath(context, (CGPathRef) path.GetNativePath());
1434 CGContextStrokePath(context);
1436 #endif // wxUSE_GRAPHICS_CONTEXT
1439 wxpeer->MacPaintChildrenBorders();
1440 wxpeer->MacSetCGContextRef( NULL );
1441 CGContextRestoreGState( context );
1444 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1446 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1448 wxpeer->OSXHandleClicked(0);
1451 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1455 void wxWidgetCocoaImpl::controlTextDidChange()
1457 wxWindow* wxpeer = (wxWindow*)GetWXPeer();
1460 // since native rtti doesn't have to be enabled and wx' rtti is not aware of the mixin wxTextEntry, workaround is needed
1461 wxTextCtrl *tc = wxDynamicCast( wxpeer , wxTextCtrl );
1462 wxComboBox *cb = wxDynamicCast( wxpeer , wxComboBox );
1464 tc->SendTextUpdatedEventIfAllowed();
1466 cb->SendTextUpdatedEventIfAllowed();
1469 wxFAIL_MSG("Unexpected class for controlTextDidChange event");
1476 #if OBJC_API_VERSION >= 2
1478 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1479 class_addMethod(c, s, i, t );
1483 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1484 { s, (char*) t, i },
1488 void wxOSXCocoaClassAddWXMethods(Class c)
1491 #if OBJC_API_VERSION < 2
1492 static objc_method wxmethods[] =
1496 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1497 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1498 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1500 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1501 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1502 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1504 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1506 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1507 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1508 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1510 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
1512 wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1513 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1514 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1516 wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1517 wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1518 wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1520 wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1522 wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
1524 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1525 wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1526 wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1527 wxOSX_CLASS_ADD_METHOD(c, @selector(resetCursorRects), (IMP) wxOSX_resetCursorRects, "v@:" )
1529 wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1530 wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1532 wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1533 wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1535 #if wxUSE_DRAG_AND_DROP
1536 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1537 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1538 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1539 wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1542 #if OBJC_API_VERSION < 2
1544 static int method_count = WXSIZEOF( wxmethods );
1545 static objc_method_list *wxmethodlist = NULL;
1546 if ( wxmethodlist == NULL )
1548 wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1549 memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1550 wxmethodlist->method_count = method_count;
1551 wxmethodlist->obsolete = 0;
1553 class_addMethods( c, wxmethodlist );
1558 // C++ implementation class
1561 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1563 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl, bool isUserPane ) :
1564 wxWidgetImpl( peer, isRootControl, isUserPane )
1569 // check if the user wants to create the control initially hidden
1570 if ( !peer->IsShown() )
1571 SetVisibility(false);
1573 // gc aware handling
1575 CFRetain(m_osxView);
1576 [m_osxView release];
1579 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1584 void wxWidgetCocoaImpl::Init()
1588 m_lastKeyDownEvent = NULL;
1589 m_hasEditor = false;
1592 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1594 RemoveAssociations( this );
1596 if ( !IsRootControl() )
1598 NSView *sv = [m_osxView superview];
1600 [m_osxView removeFromSuperview];
1602 // gc aware handling
1604 CFRelease(m_osxView);
1607 bool wxWidgetCocoaImpl::IsVisible() const
1609 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1612 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1614 [m_osxView setHidden:(visible ? NO:YES)];
1617 // ----------------------------------------------------------------------------
1618 // window animation stuff
1619 // ----------------------------------------------------------------------------
1621 // define a delegate used to refresh the window during animation
1622 @interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
1628 - (id)init:(wxWindow *)win;
1632 // NSAnimationDelegate methods
1633 - (void)animationDidEnd:(NSAnimation*)animation;
1634 - (void)animation:(NSAnimation*)animation
1635 didReachProgressMark:(NSAnimationProgress)progress;
1638 @implementation wxNSAnimationDelegate
1640 - (id)init:(wxWindow *)win
1642 self = [super init];
1655 - (void)animation:(NSAnimation*)animation
1656 didReachProgressMark:(NSAnimationProgress)progress
1658 wxUnusedVar(animation);
1659 wxUnusedVar(progress);
1661 m_win->SendSizeEvent();
1662 m_win->MacOnInternalSize();
1665 - (void)animationDidEnd:(NSAnimation*)animation
1667 wxUnusedVar(animation);
1675 wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1677 wxShowEffect effect,
1680 // create the dictionary describing the animation to perform on this view
1682 viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1683 NSMutableDictionary * const
1684 dict = [NSMutableDictionary dictionaryWithCapacity:4];
1685 [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1687 // determine the start and end rectangles assuming we're hiding the window
1688 const wxRect rectOrig = win->GetRect();
1696 if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1697 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1698 effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1699 else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1700 effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1701 effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1702 else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1703 effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1704 effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1705 else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1706 effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1707 effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1712 case wxSHOW_EFFECT_ROLL_TO_LEFT:
1713 case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1717 case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1718 case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1719 rectEnd.x = rectStart.GetRight();
1723 case wxSHOW_EFFECT_ROLL_TO_TOP:
1724 case wxSHOW_EFFECT_SLIDE_TO_TOP:
1728 case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1729 case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1730 rectEnd.y = rectStart.GetBottom();
1734 case wxSHOW_EFFECT_EXPAND:
1735 rectEnd.x = rectStart.x + rectStart.width / 2;
1736 rectEnd.y = rectStart.y + rectStart.height / 2;
1741 case wxSHOW_EFFECT_BLEND:
1742 [dict setObject:(show ? NSViewAnimationFadeInEffect
1743 : NSViewAnimationFadeOutEffect)
1744 forKey:NSViewAnimationEffectKey];
1747 case wxSHOW_EFFECT_NONE:
1748 case wxSHOW_EFFECT_MAX:
1749 wxFAIL_MSG( "unexpected animation effect" );
1753 wxFAIL_MSG( "unknown animation effect" );
1759 // we need to restore it to the original rectangle instead of making it
1761 wxSwap(rectStart, rectEnd);
1763 // and as the window is currently hidden, we need to show it for the
1764 // animation to be visible at all (but don't restore it at its full
1765 // rectangle as it shouldn't appear immediately)
1766 win->SetSize(rectStart);
1770 NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1771 ? [(NSView *)viewOrWin superview]
1773 const NSRect rStart = wxToNSRect(parentView, rectStart);
1774 const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1776 [dict setObject:[NSValue valueWithRect:rStart]
1777 forKey:NSViewAnimationStartFrameKey];
1778 [dict setObject:[NSValue valueWithRect:rEnd]
1779 forKey:NSViewAnimationEndFrameKey];
1781 // create an animation using the values in the above dictionary
1782 NSViewAnimation * const
1783 anim = [[NSViewAnimation alloc]
1784 initWithViewAnimations:[NSArray arrayWithObject:dict]];
1788 // what is a good default duration? Windows uses 200ms, Web frameworks
1789 // use anything from 250ms to 1s... choose something in the middle
1793 [anim setDuration:timeout/1000.]; // duration is in seconds here
1795 // if the window being animated changes its layout depending on its size
1796 // (which is almost always the case) we need to redo it during animation
1798 // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1799 // controls in wxInfoBar visibly jump around)
1800 const int NUM_LAYOUTS = 20;
1801 for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1802 [anim addProgressMark:f];
1804 wxNSAnimationDelegate * const
1805 animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1806 [anim setDelegate:animDelegate];
1807 [anim startAnimation];
1809 // Cocoa is capable of doing animation asynchronously or even from separate
1810 // thread but wx API doesn't provide any way to be notified about the
1811 // animation end and without this we really must ensure that the window has
1812 // the expected (i.e. the same as if a simple Show() had been used) size
1813 // when we return, so block here until the animation finishes
1815 // notice that because the default animation mode is NSAnimationBlocking,
1816 // no user input events ought to be processed from here
1818 wxEventLoopGuarantor ensureEventLoopExistence;
1819 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1820 while ( ![animDelegate isDone] )
1826 // NSViewAnimation is smart enough to hide the NSView being animated at
1827 // the end but we also must ensure that it's hidden for wx too
1830 // and we must also restore its size because it isn't expected to
1831 // change just because the window was hidden
1832 win->SetSize(rectOrig);
1836 // refresh it once again after the end to ensure that everything is in
1838 win->SendSizeEvent();
1839 win->MacOnInternalSize();
1842 [anim setDelegate:nil];
1843 [animDelegate release];
1849 bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
1850 wxShowEffect effect,
1853 return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
1856 /* note that the drawing order between siblings is not defined under 10.4 */
1857 /* only starting from 10.5 the subview order is respected */
1859 /* NSComparisonResult is typedef'd as an enum pre-Leopard but typedef'd as
1860 * NSInteger post-Leopard. Pre-Leopard the Cocoa toolkit expects a function
1861 * returning int and not NSComparisonResult. Post-Leopard the Cocoa toolkit
1862 * expects a function returning the new non-enum NSComparsionResult.
1863 * Hence we create a typedef named CocoaWindowCompareFunctionResult.
1865 #if defined(NSINTEGER_DEFINED)
1866 typedef NSComparisonResult CocoaWindowCompareFunctionResult;
1868 typedef int CocoaWindowCompareFunctionResult;
1871 class CocoaWindowCompareContext
1873 wxDECLARE_NO_COPY_CLASS(CocoaWindowCompareContext);
1875 CocoaWindowCompareContext(); // Not implemented
1876 CocoaWindowCompareContext(NSView *target, NSArray *subviews)
1879 // Cocoa sorts subviews in-place.. make a copy
1880 m_subviews = [subviews copy];
1883 ~CocoaWindowCompareContext()
1884 { // release the copy
1885 [m_subviews release];
1888 { return m_target; }
1891 { return m_subviews; }
1893 /* Helper function that returns the comparison based off of the original ordering */
1894 CocoaWindowCompareFunctionResult CompareUsingOriginalOrdering(id first, id second)
1896 NSUInteger firstI = [m_subviews indexOfObjectIdenticalTo:first];
1897 NSUInteger secondI = [m_subviews indexOfObjectIdenticalTo:second];
1898 // NOTE: If either firstI or secondI is NSNotFound then it will be NSIntegerMax and thus will
1899 // likely compare higher than the other view which is reasonable considering the only way that
1900 // can happen is if the subview was added after our call to subviews but before the call to
1901 // sortSubviewsUsingFunction:context:. Thus we don't bother checking. Particularly because
1902 // that case should never occur anyway because that would imply a multi-threaded GUI call
1903 // which is a big no-no with Cocoa.
1905 // Subviews are ordered from back to front meaning one that is already lower will have an lower index.
1906 NSComparisonResult result = (firstI < secondI)
1907 ? NSOrderedAscending /* -1 */
1908 : (firstI > secondI)
1909 ? NSOrderedDescending /* 1 */
1910 : NSOrderedSame /* 0 */;
1915 /* The subview we are trying to Raise or Lower */
1917 /* A copy of the original array of subviews */
1918 NSArray *m_subviews;
1921 /* Causes Cocoa to raise the target view to the top of the Z-Order by telling the sort function that
1922 * the target view is always higher than every other view. When comparing two views neither of
1923 * which is the target, it returns the correct response based on the original ordering
1925 static CocoaWindowCompareFunctionResult CocoaRaiseWindowCompareFunction(id first, id second, void *ctx)
1927 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
1928 // first should be ordered higher
1929 if(first==compareContext->target())
1930 return NSOrderedDescending;
1931 // second should be ordered higher
1932 if(second==compareContext->target())
1933 return NSOrderedAscending;
1934 return compareContext->CompareUsingOriginalOrdering(first,second);
1937 void wxWidgetCocoaImpl::Raise()
1939 NSView* nsview = m_osxView;
1941 NSView *superview = [nsview superview];
1942 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
1944 [superview sortSubviewsUsingFunction:
1945 CocoaRaiseWindowCompareFunction
1946 context: &compareContext];
1950 /* Causes Cocoa to lower the target view to the bottom of the Z-Order by telling the sort function that
1951 * the target view is always lower than every other view. When comparing two views neither of
1952 * which is the target, it returns the correct response based on the original ordering
1954 static CocoaWindowCompareFunctionResult CocoaLowerWindowCompareFunction(id first, id second, void *ctx)
1956 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
1957 // first should be ordered lower
1958 if(first==compareContext->target())
1959 return NSOrderedAscending;
1960 // second should be ordered lower
1961 if(second==compareContext->target())
1962 return NSOrderedDescending;
1963 return compareContext->CompareUsingOriginalOrdering(first,second);
1966 void wxWidgetCocoaImpl::Lower()
1968 NSView* nsview = m_osxView;
1970 NSView *superview = [nsview superview];
1971 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
1973 [superview sortSubviewsUsingFunction:
1974 CocoaLowerWindowCompareFunction
1975 context: &compareContext];
1978 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
1983 // We should do something like this, but it wasn't working in 10.4.
1984 if (GetNeedsDisplay() )
1988 NSRect r = wxToNSRect( [m_osxView superview], *rect );
1989 NSSize offset = NSMakeSize((float)dx, (float)dy);
1990 [m_osxView scrollRect:r by:offset];
1994 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
1996 wxWindowMac* parent = GetWXPeer()->GetParent();
1997 // under Cocoa we might have a contentView in the wxParent to which we have to
1998 // adjust the coordinates
1999 if (parent && [m_osxView superview] != parent->GetHandle() )
2001 int cx = 0,cy = 0,cw = 0,ch = 0;
2002 if ( parent->GetPeer() )
2004 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2009 [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
2010 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
2011 [m_osxView setFrame:r];
2012 [[m_osxView superview] setNeedsDisplayInRect:r];
2014 wxNSView* wxview = (wxNSView*)m_osxView;
2016 if ([wxview respondsToSelector:@selector(updateTrackingArea)] )
2017 [wxview updateTrackingArea];
2020 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
2022 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
2026 // under Cocoa we might have a contentView in the wxParent to which we have to
2027 // adjust the coordinates
2028 wxWindowMac* parent = GetWXPeer()->GetParent();
2029 if (parent && [m_osxView superview] != parent->GetHandle() )
2031 int cx = 0,cy = 0,cw = 0,ch = 0;
2032 if ( parent->GetPeer() )
2034 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2041 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
2043 NSRect rect = [m_osxView frame];
2044 width = (int)rect.size.width;
2045 height = (int)rect.size.height;
2048 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
2050 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
2052 NSView* cv = [m_osxView contentView];
2054 NSRect bounds = [m_osxView bounds];
2055 NSRect rect = [cv frame];
2057 int y = (int)rect.origin.y;
2058 int x = (int)rect.origin.x;
2059 if ( ![ m_osxView isFlipped ] )
2060 y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
2063 width = (int)rect.size.width;
2064 height = (int)rect.size.height;
2069 GetSize( width, height );
2073 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
2076 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
2078 [m_osxView setNeedsDisplay:YES];
2081 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
2083 return [m_osxView needsDisplay];
2086 bool wxWidgetCocoaImpl::CanFocus() const
2088 return [m_osxView canBecomeKeyView] == YES;
2091 bool wxWidgetCocoaImpl::HasFocus() const
2093 return ( FindFocus() == m_osxView );
2096 bool wxWidgetCocoaImpl::SetFocus()
2101 // TODO remove if no issues arise: should not raise the window, only assign focus
2102 //[[m_osxView window] makeKeyAndOrderFront:nil] ;
2103 [[m_osxView window] makeFirstResponder: m_osxView] ;
2108 void wxWidgetCocoaImpl::RemoveFromParent()
2110 [m_osxView removeFromSuperview];
2113 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
2115 NSView* container = parent->GetWXWidget() ;
2116 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
2117 [container addSubview:m_osxView];
2120 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
2122 NSView* targetView = m_osxView;
2123 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2124 targetView = [(NSScrollView*) m_osxView documentView];
2126 if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
2128 [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2129 green:(CGFloat) (col.Green() / 255.0)
2130 blue:(CGFloat) (col.Blue() / 255.0)
2131 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2135 bool wxWidgetCocoaImpl::SetBackgroundStyle( wxBackgroundStyle style )
2137 BOOL opaque = ( style == wxBG_STYLE_PAINT );
2139 if ( [m_osxView respondsToSelector:@selector(setOpaque:) ] )
2141 [m_osxView setOpaque: opaque];
2147 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
2149 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
2151 wxCFStringRef cf( title , encoding );
2152 [m_osxView setTitle:cf.AsNSString()];
2154 else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
2156 wxCFStringRef cf( title , encoding );
2157 [m_osxView setStringValue:cf.AsNSString()];
2162 void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
2164 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
2165 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
2166 *pt = wxFromNSPoint( to->GetWXWidget(), p );
2169 wxInt32 wxWidgetCocoaImpl::GetValue() const
2171 return [(NSControl*)m_osxView intValue];
2174 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
2176 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
2178 [m_osxView setIntValue:v];
2180 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
2182 [m_osxView setFloatValue:(double)v];
2184 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
2186 [m_osxView setDoubleValue:(double)v];
2190 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
2192 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
2194 [m_osxView setMinValue:(double)v];
2198 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
2200 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
2202 [m_osxView setMaxValue:(double)v];
2206 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
2208 if ( [m_osxView respondsToSelector:@selector(minValue)] )
2210 return (int)[m_osxView minValue];
2215 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
2217 if ( [m_osxView respondsToSelector:@selector(maxValue)] )
2219 return (int)[m_osxView maxValue];
2224 wxBitmap wxWidgetCocoaImpl::GetBitmap() const
2228 // TODO: how to create a wxBitmap from NSImage?
2230 if ( [m_osxView respondsToSelector:@selector(image:)] )
2231 bmp = [m_osxView image];
2237 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
2239 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
2242 [m_osxView setImage:bitmap.GetNSImage()];
2244 [m_osxView setImage:nil];
2246 [m_osxView setNeedsDisplay:YES];
2250 void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
2252 if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
2254 NSCellImagePosition pos;
2274 wxFAIL_MSG( "invalid image position" );
2278 [m_osxView setImagePosition:pos];
2282 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
2284 // implementation in subclass
2287 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
2289 r->x = r->y = r->width = r->height = 0;
2291 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
2293 NSRect former = [m_osxView frame];
2294 [m_osxView sizeToFit];
2295 NSRect best = [m_osxView frame];
2296 [m_osxView setFrame:former];
2297 r->width = (int)best.size.width;
2298 r->height = (int)best.size.height;
2302 bool wxWidgetCocoaImpl::IsEnabled() const
2304 NSView* targetView = m_osxView;
2305 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2306 targetView = [(NSScrollView*) m_osxView documentView];
2308 if ( [targetView respondsToSelector:@selector(isEnabled) ] )
2309 return [targetView isEnabled];
2313 void wxWidgetCocoaImpl::Enable( bool enable )
2315 NSView* targetView = m_osxView;
2316 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2317 targetView = [(NSScrollView*) m_osxView documentView];
2319 if ( [targetView respondsToSelector:@selector(setEnabled:) ] )
2320 [targetView setEnabled:enable];
2323 void wxWidgetCocoaImpl::PulseGauge()
2327 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
2331 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
2333 NSControlSize size = NSRegularControlSize;
2337 case wxWINDOW_VARIANT_NORMAL :
2338 size = NSRegularControlSize;
2341 case wxWINDOW_VARIANT_SMALL :
2342 size = NSSmallControlSize;
2345 case wxWINDOW_VARIANT_MINI :
2346 size = NSMiniControlSize;
2349 case wxWINDOW_VARIANT_LARGE :
2350 size = NSRegularControlSize;
2354 wxFAIL_MSG(wxT("unexpected window variant"));
2357 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
2358 [m_osxView setControlSize:size];
2359 else if ([m_osxView respondsToSelector:@selector(cell)])
2361 id cell = [(id)m_osxView cell];
2362 if ([cell respondsToSelector:@selector(setControlSize:)])
2363 [cell setControlSize:size];
2367 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&col, long, bool)
2369 if ([m_osxView respondsToSelector:@selector(setFont:)])
2370 [m_osxView setFont: font.OSXGetNSFont()];
2371 if ([m_osxView respondsToSelector:@selector(setTextColor:)])
2372 [m_osxView setTextColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2373 green:(CGFloat) (col.Green() / 255.0)
2374 blue:(CGFloat) (col.Blue() / 255.0)
2375 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2378 void wxWidgetCocoaImpl::SetToolTip(wxToolTip* tooltip)
2382 wxCFStringRef cf( tooltip->GetTip() , m_wxPeer->GetFont().GetEncoding() );
2383 [m_osxView setToolTip: cf.AsNSString()];
2387 [m_osxView setToolTip:nil];
2391 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
2393 WXWidget c = control ? control : (WXWidget) m_osxView;
2394 wxWidgetImpl::Associate( c, this ) ;
2395 if ([c respondsToSelector:@selector(setAction:)])
2398 [c setAction: @selector(controlAction:)];
2399 if ([c respondsToSelector:@selector(setDoubleAction:)])
2401 [c setDoubleAction: @selector(controlDoubleAction:)];
2407 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
2409 wxKeyEvent wxevent(wxEVT_CHAR);
2410 SetupKeyEvent( wxevent, event, text );
2412 return GetWXPeer()->OSXHandleKeyEvent(wxevent);
2415 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
2417 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
2418 SetupKeyEvent( wxevent, event );
2420 // Generate wxEVT_CHAR_HOOK before sending any other events but only when
2421 // the key is pressed, not when it's released (the type of wxevent is
2422 // changed by SetupKeyEvent() so it can be wxEVT_KEY_UP too by now).
2423 if ( wxevent.GetEventType() == wxEVT_KEY_DOWN )
2425 wxKeyEvent eventHook(wxEVT_CHAR_HOOK, wxevent);
2426 if ( GetWXPeer()->OSXHandleKeyEvent(eventHook)
2427 && !eventHook.IsNextEventAllowed() )
2431 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
2433 // this will fire higher level events, like insertText, to help
2434 // us handle EVT_CHAR, etc.
2438 if ( IsUserPane() && [event type] == NSKeyDown)
2440 long keycode = wxOSXTranslateCocoaKey( event, wxEVT_CHAR );
2442 if ( (keycode > 0 && keycode < WXK_SPACE) || keycode == WXK_DELETE || keycode >= WXK_START )
2444 // eventually we could setup a doCommandBySelector catcher and retransform this into the wx key chars
2445 wxKeyEvent wxevent2(wxevent) ;
2446 wxevent2.SetEventType(wxEVT_CHAR);
2447 wxevent2.m_keyCode = keycode;
2448 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2452 if ( !wxevent.CmdDown() )
2454 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2455 [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
2457 [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
2467 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
2469 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
2470 SetupMouseEvent(wxevent , event) ;
2471 wxWindow* wxp = GetWXPeer();
2473 wxToolTip::RelayEvent( wxp , wxevent);
2475 return wxp->HandleWindowEvent(wxevent);
2478 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
2480 wxWindow* thisWindow = GetWXPeer();
2481 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
2483 thisWindow->MacInvalidateBorders();
2486 if ( receivedFocus )
2488 wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
2489 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
2490 thisWindow->HandleWindowEvent(eventFocus);
2493 if ( thisWindow->GetCaret() )
2494 thisWindow->GetCaret()->OnSetFocus();
2497 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
2498 event.SetEventObject(thisWindow);
2500 event.SetWindow(otherWindow->GetWXPeer());
2501 thisWindow->HandleWindowEvent(event) ;
2503 else // !receivedFocuss
2506 if ( thisWindow->GetCaret() )
2507 thisWindow->GetCaret()->OnKillFocus();
2510 wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
2512 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
2513 event.SetEventObject(thisWindow);
2515 event.SetWindow(otherWindow->GetWXPeer());
2516 thisWindow->HandleWindowEvent(event) ;
2520 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
2524 NSPoint location = [NSEvent mouseLocation];
2525 location = [[m_osxView window] convertScreenToBase:location];
2526 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
2528 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
2530 [(NSCursor*)cursor.GetHCURSOR() set];
2533 [[m_osxView window] invalidateCursorRectsForView:m_osxView];
2536 void wxWidgetCocoaImpl::CaptureMouse()
2538 [[m_osxView window] disableCursorRects];
2541 void wxWidgetCocoaImpl::ReleaseMouse()
2543 [[m_osxView window] enableCursorRects];
2546 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
2548 m_isFlipped = flipped;
2555 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
2556 wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
2557 long WXUNUSED(style), long WXUNUSED(extraStyle))
2559 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
2560 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
2562 // temporary hook for dnd
2563 [v registerForDraggedTypes:[NSArray arrayWithObjects:
2564 NSStringPboardType, NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSPDFPboardType, nil]];
2566 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v, false, true );
2570 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
2572 NSWindow* tlw = now->GetWXWindow();
2574 wxWidgetCocoaImpl* c = NULL;
2575 if ( now->IsNativeWindowWrapper() )
2577 NSView* cv = [tlw contentView];
2578 c = new wxWidgetCocoaImpl( now, cv, true );
2579 // increase ref count, because the impl destructor will decrement it again
2581 if ( !now->IsShown() )
2587 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2588 c = new wxWidgetCocoaImpl( now, v, true );
2589 c->InstallEventHandler();
2590 [tlw setContentView:v];