1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/cocoa/window.mm
3 // Purpose: widgets (non tlw) for cocoa
4 // Author: Stefan Csomor
8 // Copyright: (c) Stefan Csomor
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 #include "wx/wxprec.h"
15 #include "wx/dcclient.h"
18 #include "wx/textctrl.h"
19 #include "wx/combobox.h"
23 #include "wx/osx/private.h"
26 #include "wx/evtloop.h"
32 #if wxUSE_DRAG_AND_DROP
37 #include "wx/tooltip.h"
40 #include <objc/objc-runtime.h>
42 // Get the window with the focus
44 NSView* GetViewFromResponder( NSResponder* responder )
47 if ( [responder isKindOfClass:[NSTextView class]] )
49 NSView* delegate = (NSView*) [(NSTextView*)responder delegate];
50 if ( [delegate isKindOfClass:[NSTextField class] ] )
53 view = (NSView*) responder;
57 if ( [responder isKindOfClass:[NSView class]] )
58 view = (NSView*) responder;
63 NSView* GetFocusedViewInWindow( NSWindow* keyWindow )
65 NSView* focusedView = nil;
66 if ( keyWindow != nil )
67 focusedView = GetViewFromResponder([keyWindow firstResponder]);
72 WXWidget wxWidgetImpl::FindFocus()
74 return GetFocusedViewInWindow( [NSApp keyWindow] );
77 NSRect wxOSXGetFrameForControl( wxWindowMac* window , const wxPoint& pos , const wxSize &size , bool adjustForOrigin )
81 window->MacGetBoundsForControl( pos , size , x , y, w, h , adjustForOrigin ) ;
82 wxRect bounds(x,y,w,h);
83 NSView* sv = (window->GetParent()->GetHandle() );
85 return wxToNSRect( sv, bounds );
88 @interface wxNSView : NSView
90 NSTrackingRectTag rectTag;
91 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
92 NSTrackingArea* _trackingArea;
96 // the tracking tag is needed to track mouse enter / exit events
97 - (void) setTrackingTag: (NSTrackingRectTag)tag;
98 - (NSTrackingRectTag) trackingTag;
99 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
100 // under 10.5 we can also track mouse moved events on non-focused windows if
101 // we use the new NSTrackingArea APIs.
102 - (void) updateTrackingArea;
103 - (NSTrackingArea*) trackingArea;
107 @interface NSView(PossibleMethods)
108 - (void)setTitle:(NSString *)aString;
109 - (void)setStringValue:(NSString *)aString;
110 - (void)setIntValue:(int)anInt;
111 - (void)setFloatValue:(float)aFloat;
112 - (void)setDoubleValue:(double)aDouble;
116 - (void)setMinValue:(double)aDouble;
117 - (void)setMaxValue:(double)aDouble;
122 - (void)setEnabled:(BOOL)flag;
124 - (void)setImage:(NSImage *)image;
125 - (void)setControlSize:(NSControlSize)size;
127 - (void)setFont:(NSFont *)fontObject;
131 - (void)setTarget:(id)anObject;
132 - (void)setAction:(SEL)aSelector;
133 - (void)setDoubleAction:(SEL)aSelector;
134 - (void)setBackgroundColor:(NSColor*)aColor;
135 - (void)setOpaque:(BOOL)opaque;
136 - (void)setTextColor:(NSColor *)color;
137 - (void)setImagePosition:(NSCellImagePosition)aPosition;
140 // in case we want to use the native tooltip callbacks
144 @interface NSView(wxToolTip)
145 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)userData;
148 @implementation NSView(wxToolTip)
150 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)userData {
151 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( view );
161 // The following code is a combination of the code listed here:
162 // http://lists.apple.com/archives/cocoa-dev/2008/Apr/msg01582.html
163 // (which can't be used because KLGetCurrentKeyboardLayout etc aren't 64-bit)
164 // and the code here:
165 // http://inquisitivecocoa.com/category/objective-c/
166 @interface NSEvent (OsGuiUtilsAdditions)
167 - (NSString*) charactersIgnoringModifiersIncludingShift;
170 @implementation NSEvent (OsGuiUtilsAdditions)
171 - (NSString*) charactersIgnoringModifiersIncludingShift {
172 // First try -charactersIgnoringModifiers and look for keys which UCKeyTranslate translates
173 // differently than AppKit.
174 NSString* c = [self charactersIgnoringModifiers];
175 if ([c length] == 1) {
176 unichar codepoint = [c characterAtIndex:0];
177 if ((codepoint >= 0xF700 && codepoint <= 0xF8FF) || codepoint == 0x7F) {
181 // This is not a "special" key, so ask UCKeyTranslate to give us the character with no
182 // modifiers attached. Actually, that's not quite accurate; we attach the Command modifier
183 // which hints the OS to use Latin characters where possible, which is generally what we want.
184 NSString* result = @"";
185 TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
186 CFDataRef uchr = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
187 CFRelease(currentKeyboard);
189 // this can happen for some non-U.S. input methods (eg. Romaji or Hiragana)
192 const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout*)CFDataGetBytePtr(uchr);
193 if (keyboardLayout) {
194 UInt32 deadKeyState = 0;
195 UniCharCount maxStringLength = 255;
196 UniCharCount actualStringLength = 0;
197 UniChar unicodeString[maxStringLength];
199 OSStatus status = UCKeyTranslate(keyboardLayout,
202 cmdKey >> 8, // force the Command key to "on"
204 kUCKeyTranslateNoDeadKeysMask,
211 result = [NSString stringWithCharacters:unicodeString length:(NSInteger)actualStringLength];
217 long wxOSXTranslateCocoaKey( NSEvent* event, int eventType )
221 if ([event type] != NSFlagsChanged)
223 NSString* s = [event charactersIgnoringModifiersIncludingShift];
224 // backspace char reports as delete w/modifiers for some reason
227 if ( eventType == wxEVT_CHAR && ([event modifierFlags] & NSControlKeyMask) && ( [s characterAtIndex:0] >= 'a' && [s characterAtIndex:0] <= 'z' ) )
229 retval = WXK_CONTROL_A + ([s characterAtIndex:0] - 'a');
233 switch ( [s characterAtIndex:0] )
240 case NSUpArrowFunctionKey :
243 case NSDownArrowFunctionKey :
246 case NSLeftArrowFunctionKey :
249 case NSRightArrowFunctionKey :
252 case NSInsertFunctionKey :
255 case NSDeleteFunctionKey :
258 case NSHomeFunctionKey :
261 // case NSBeginFunctionKey :
262 // retval = WXK_BEGIN;
264 case NSEndFunctionKey :
267 case NSPageUpFunctionKey :
270 case NSPageDownFunctionKey :
271 retval = WXK_PAGEDOWN;
273 case NSHelpFunctionKey :
277 int intchar = [s characterAtIndex: 0];
278 if ( intchar >= NSF1FunctionKey && intchar <= NSF24FunctionKey )
279 retval = WXK_F1 + (intchar - NSF1FunctionKey );
280 else if ( intchar > 0 && intchar < 32 )
288 // Some keys don't seem to have constants. The code mimics the approach
289 // taken by WebKit. See:
290 // http://trac.webkit.org/browser/trunk/WebCore/platform/mac/KeyEventMac.mm
291 switch( [event keyCode] )
296 retval = WXK_CONTROL;
300 retval = WXK_CAPITAL;
303 case 56: // Left Shift
304 case 60: // Right Shift
309 case 61: // Right Alt
313 case 59: // Left Ctrl
314 case 62: // Right Ctrl
315 retval = WXK_RAW_CONTROL;
327 retval = WXK_NUMPAD_DIVIDE;
330 retval = WXK_NUMPAD_MULTIPLY;
333 retval = WXK_NUMPAD_SUBTRACT;
336 retval = WXK_NUMPAD_ADD;
339 retval = WXK_NUMPAD_ENTER;
342 retval = WXK_NUMPAD_DECIMAL;
345 retval = WXK_NUMPAD0;
348 retval = WXK_NUMPAD1;
351 retval = WXK_NUMPAD2;
354 retval = WXK_NUMPAD3;
357 retval = WXK_NUMPAD4;
360 retval = WXK_NUMPAD5;
363 retval = WXK_NUMPAD6;
366 retval = WXK_NUMPAD7;
369 retval = WXK_NUMPAD8;
372 retval = WXK_NUMPAD9;
375 //retval = [event keyCode];
381 void wxWidgetCocoaImpl::SetupKeyEvent(wxKeyEvent &wxevent , NSEvent * nsEvent, NSString* charString)
383 UInt32 modifiers = [nsEvent modifierFlags] ;
384 int eventType = [nsEvent type];
386 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
387 wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
388 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
389 wxevent.m_controlDown = modifiers & NSCommandKeyMask;
391 wxevent.m_rawCode = [nsEvent keyCode];
392 wxevent.m_rawFlags = modifiers;
394 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
397 if ( eventType != NSFlagsChanged )
399 NSString* nschars = [[nsEvent charactersIgnoringModifiersIncludingShift] uppercaseString];
402 // if charString is set, it did not come from key up / key down
403 wxevent.SetEventType( wxEVT_CHAR );
404 chars = wxCFStringRef::AsString(charString);
408 chars = wxCFStringRef::AsString(nschars);
412 int aunichar = chars.Length() > 0 ? chars[0] : 0;
415 if (wxevent.GetEventType() != wxEVT_CHAR)
417 keyval = wxOSXTranslateCocoaKey(nsEvent, wxevent.GetEventType()) ;
421 wxevent.SetEventType( wxEVT_KEY_DOWN ) ;
424 wxevent.SetEventType( wxEVT_KEY_UP ) ;
426 case NSFlagsChanged :
430 wxevent.SetEventType( wxevent.m_controlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
433 wxevent.SetEventType( wxevent.m_shiftDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
436 wxevent.SetEventType( wxevent.m_altDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
438 case WXK_RAW_CONTROL:
439 wxevent.SetEventType( wxevent.m_rawControlDown ? wxEVT_KEY_DOWN : wxEVT_KEY_UP);
450 if ( wxevent.GetEventType() == wxEVT_KEY_UP || wxevent.GetEventType() == wxEVT_KEY_DOWN )
451 keyval = wxToupper( aunichar ) ;
457 // OS X generates events with key codes in Unicode private use area for
458 // unprintable symbols such as cursor arrows (WXK_UP is mapped to U+F700)
459 // and function keys (WXK_F2 is U+F705). We don't want to use them as the
460 // result of wxKeyEvent::GetUnicodeKey() however as it's supposed to return
461 // WXK_NONE for "non characters" so explicitly exclude them.
463 // We only exclude the private use area inside the Basic Multilingual Plane
464 // as key codes beyond it don't seem to be currently used.
465 if ( !(aunichar >= 0xe000 && aunichar < 0xf900) )
466 wxevent.m_uniChar = aunichar;
468 wxevent.m_keyCode = keyval;
470 wxWindowMac* peer = GetWXPeer();
473 wxevent.SetEventObject(peer);
474 wxevent.SetId(peer->GetId()) ;
478 UInt32 g_lastButton = 0 ;
479 bool g_lastButtonWasFakeRight = false ;
481 // better scroll wheel support
482 // see http://lists.apple.com/archives/cocoa-dev/2007/Feb/msg00050.html
484 @interface NSEvent (DeviceDelta)
485 - (CGFloat)deviceDeltaX;
486 - (CGFloat)deviceDeltaY;
489 void wxWidgetCocoaImpl::SetupMouseEvent( wxMouseEvent &wxevent , NSEvent * nsEvent )
491 int eventType = [nsEvent type];
492 UInt32 modifiers = [nsEvent modifierFlags] ;
494 NSPoint locationInWindow = [nsEvent locationInWindow];
496 // adjust coordinates for the window of the target view
497 if ( [nsEvent window] != [m_osxView window] )
499 if ( [nsEvent window] != nil )
500 locationInWindow = [[nsEvent window] convertBaseToScreen:locationInWindow];
502 if ( [m_osxView window] != nil )
503 locationInWindow = [[m_osxView window] convertScreenToBase:locationInWindow];
506 NSPoint locationInView = [m_osxView convertPoint:locationInWindow fromView:nil];
507 wxPoint locationInViewWX = wxFromNSPoint( m_osxView, locationInView );
509 // these parameters are not given for all events
510 UInt32 button = [nsEvent buttonNumber];
511 UInt32 clickCount = 0;
513 wxevent.m_x = locationInViewWX.x;
514 wxevent.m_y = locationInViewWX.y;
515 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
516 wxevent.m_rawControlDown = modifiers & NSControlKeyMask;
517 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
518 wxevent.m_controlDown = modifiers & NSCommandKeyMask;
519 wxevent.SetTimestamp( (int)([nsEvent timestamp] * 1000) ) ;
521 UInt32 mouseChord = 0;
525 case NSLeftMouseDown :
526 case NSLeftMouseDragged :
529 case NSRightMouseDown :
530 case NSRightMouseDragged :
533 case NSOtherMouseDown :
534 case NSOtherMouseDragged :
539 // a control click is interpreted as a right click
540 bool thisButtonIsFakeRight = false ;
541 if ( button == 0 && (modifiers & NSControlKeyMask) )
544 thisButtonIsFakeRight = true ;
547 // otherwise we report double clicks by connecting a left click with a ctrl-left click
548 if ( clickCount > 1 && button != g_lastButton )
551 // we must make sure that our synthetic 'right' button corresponds in
552 // mouse down, moved and mouse up, and does not deliver a right down and left up
555 case NSLeftMouseDown :
556 case NSRightMouseDown :
557 case NSOtherMouseDown :
558 g_lastButton = button ;
559 g_lastButtonWasFakeRight = thisButtonIsFakeRight ;
566 g_lastButtonWasFakeRight = false ;
568 else if ( g_lastButton == 1 && g_lastButtonWasFakeRight )
569 button = g_lastButton ;
571 // Adjust the chord mask to remove the primary button and add the
572 // secondary button. It is possible that the secondary button is
573 // already pressed, e.g. on a mouse connected to a laptop, but this
574 // possibility is ignored here:
575 if( thisButtonIsFakeRight && ( mouseChord & 1U ) )
576 mouseChord = ((mouseChord & ~1U) | 2U);
579 wxevent.m_leftDown = true ;
581 wxevent.m_rightDown = true ;
583 wxevent.m_middleDown = true ;
585 // translate into wx types
588 case NSLeftMouseDown :
589 case NSRightMouseDown :
590 case NSOtherMouseDown :
591 clickCount = [nsEvent clickCount];
595 wxevent.SetEventType( clickCount > 1 ? wxEVT_LEFT_DCLICK : wxEVT_LEFT_DOWN ) ;
599 wxevent.SetEventType( clickCount > 1 ? wxEVT_RIGHT_DCLICK : wxEVT_RIGHT_DOWN ) ;
603 wxevent.SetEventType( clickCount > 1 ? wxEVT_MIDDLE_DCLICK : wxEVT_MIDDLE_DOWN ) ;
612 case NSRightMouseUp :
613 case NSOtherMouseUp :
614 clickCount = [nsEvent clickCount];
618 wxevent.SetEventType( wxEVT_LEFT_UP ) ;
622 wxevent.SetEventType( wxEVT_RIGHT_UP ) ;
626 wxevent.SetEventType( wxEVT_MIDDLE_UP ) ;
639 wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ;
641 // see http://developer.apple.com/qa/qa2005/qa1453.html
642 // for more details on why we have to look for the exact type
644 const EventRef cEvent = (EventRef) [nsEvent eventRef];
645 bool isMouseScrollEvent = false;
647 isMouseScrollEvent = ::GetEventKind(cEvent) == kEventMouseScroll;
649 if ( isMouseScrollEvent )
651 deltaX = [nsEvent deviceDeltaX];
652 deltaY = [nsEvent deviceDeltaY];
656 deltaX = ([nsEvent deltaX] * 10);
657 deltaY = ([nsEvent deltaY] * 10);
660 wxevent.m_wheelDelta = 10;
661 wxevent.m_linesPerAction = 1;
663 if ( fabs(deltaX) > fabs(deltaY) )
665 wxevent.m_wheelAxis = 1;
666 wxevent.m_wheelRotation = (int)deltaX;
670 wxevent.m_wheelRotation = (int)deltaY;
676 case NSMouseEntered :
677 wxevent.SetEventType( wxEVT_ENTER_WINDOW ) ;
680 wxevent.SetEventType( wxEVT_LEAVE_WINDOW ) ;
682 case NSLeftMouseDragged :
683 case NSRightMouseDragged :
684 case NSOtherMouseDragged :
686 wxevent.SetEventType( wxEVT_MOTION ) ;
692 wxevent.m_clickCount = clickCount;
693 wxWindowMac* peer = GetWXPeer();
696 wxevent.SetEventObject(peer);
697 wxevent.SetId(peer->GetId()) ;
701 @implementation wxNSView
705 static BOOL initialized = NO;
709 wxOSXCocoaClassAddWXMethods( self );
713 - (void) setTrackingTag: (NSTrackingRectTag)tag
718 - (NSTrackingRectTag) trackingTag
723 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
724 - (void) updateTrackingArea
728 [self removeTrackingArea: _trackingArea];
729 [_trackingArea release];
732 NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited|NSTrackingMouseMoved|NSTrackingActiveAlways;
734 NSTrackingArea* area = [[NSTrackingArea alloc] initWithRect: [self bounds] options: options owner: self userInfo: nil];
735 [self addTrackingArea: area];
737 _trackingArea = area;
740 - (NSTrackingArea*) trackingArea
742 return _trackingArea;
751 #if wxUSE_DRAG_AND_DROP
753 // see http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01244.html
754 // for details on the NSPasteboard -> PasteboardRef conversion
756 NSDragOperation wxOSX_draggingEntered( id self, SEL _cmd, id <NSDraggingInfo>sender )
758 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
760 return NSDragOperationNone;
762 return impl->draggingEntered(sender, self, _cmd);
765 void wxOSX_draggingExited( id self, SEL _cmd, id <NSDraggingInfo> sender )
767 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
771 return impl->draggingExited(sender, self, _cmd);
774 NSDragOperation wxOSX_draggingUpdated( id self, SEL _cmd, id <NSDraggingInfo>sender )
776 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
778 return NSDragOperationNone;
780 return impl->draggingUpdated(sender, self, _cmd);
783 BOOL wxOSX_performDragOperation( id self, SEL _cmd, id <NSDraggingInfo> sender )
785 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
787 return NSDragOperationNone;
789 return impl->performDragOperation(sender, self, _cmd) ? YES:NO ;
794 void wxOSX_mouseEvent(NSView* self, SEL _cmd, NSEvent *event)
796 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
800 impl->mouseEvent(event, self, _cmd);
803 BOOL wxOSX_acceptsFirstMouse(NSView* WXUNUSED(self), SEL WXUNUSED(_cmd), NSEvent *WXUNUSED(event))
805 // This is needed to support click through, otherwise the first click on a window
806 // will not do anything unless it is the active window already.
810 void wxOSX_keyEvent(NSView* self, SEL _cmd, NSEvent *event)
812 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
816 impl->keyEvent(event, self, _cmd);
819 void wxOSX_insertText(NSView* self, SEL _cmd, NSString* text)
821 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
825 impl->insertText(text, self, _cmd);
828 BOOL wxOSX_performKeyEquivalent(NSView* self, SEL _cmd, NSEvent *event)
830 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
834 return impl->performKeyEquivalent(event, self, _cmd);
837 BOOL wxOSX_acceptsFirstResponder(NSView* self, SEL _cmd)
839 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
843 return impl->acceptsFirstResponder(self, _cmd);
846 BOOL wxOSX_becomeFirstResponder(NSView* self, SEL _cmd)
848 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
852 return impl->becomeFirstResponder(self, _cmd);
855 BOOL wxOSX_resignFirstResponder(NSView* self, SEL _cmd)
857 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
861 return impl->resignFirstResponder(self, _cmd);
864 void wxOSX_resetCursorRects(NSView* self, SEL _cmd)
866 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
870 impl->resetCursorRects(self, _cmd);
873 BOOL wxOSX_isFlipped(NSView* self, SEL _cmd)
875 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
879 return impl->isFlipped(self, _cmd) ? YES:NO;
882 typedef void (*wxOSX_DrawRectHandlerPtr)(NSView* self, SEL _cmd, NSRect rect);
884 void wxOSX_drawRect(NSView* self, SEL _cmd, NSRect rect)
886 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
891 // OS X starts a NSUIHeartBeatThread for animating the default button in a
892 // dialog. This causes a drawRect of the active dialog from outside the
893 // main UI thread. This causes an occasional crash since the wx drawing
894 // objects (like wxPen) are not thread safe.
896 // Notice that NSUIHeartBeatThread seems to be undocumented and doing
897 // [NSWindow setAllowsConcurrentViewDrawing:NO] does not affect it.
898 if ( !wxThread::IsMain() )
900 if ( impl->IsUserPane() )
902 wxWindow* win = impl->GetWXPeer();
903 if ( win->UseBgCol() )
906 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
907 CGContextSaveGState( context );
909 CGContextSetFillColorWithColor( context, win->GetBackgroundColour().GetCGColor());
910 CGRect r = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
911 CGContextFillRect( context, r );
913 CGContextRestoreGState( context );
918 // just call the superclass handler, we don't need any custom wx drawing
919 // here and it seems to work fine:
920 wxOSX_DrawRectHandlerPtr
921 superimpl = (wxOSX_DrawRectHandlerPtr)
922 [[self superclass] instanceMethodForSelector:_cmd];
923 superimpl(self, _cmd, rect);
928 #endif // wxUSE_THREADS
930 return impl->drawRect(&rect, self, _cmd);
933 void wxOSX_controlAction(NSView* self, SEL _cmd, id sender)
935 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
939 impl->controlAction(self, _cmd, sender);
942 void wxOSX_controlDoubleAction(NSView* self, SEL _cmd, id sender)
944 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
948 impl->controlDoubleAction(self, _cmd, sender);
951 unsigned int wxWidgetCocoaImpl::draggingEntered(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
953 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
954 NSPasteboard *pboard = [sender draggingPasteboard];
955 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
957 wxWindow* wxpeer = GetWXPeer();
958 if ( wxpeer == NULL )
959 return NSDragOperationNone;
961 wxDropTarget* target = wxpeer->GetDropTarget();
962 if ( target == NULL )
963 return NSDragOperationNone;
965 wxDragResult result = wxDragNone;
966 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
967 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
969 if ( sourceDragMask & NSDragOperationLink )
971 else if ( sourceDragMask & NSDragOperationCopy )
973 else if ( sourceDragMask & NSDragOperationMove )
976 PasteboardRef pboardRef;
977 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
978 target->SetCurrentDragPasteboard(pboardRef);
979 result = target->OnEnter(pt.x, pt.y, result);
980 CFRelease(pboardRef);
982 NSDragOperation nsresult = NSDragOperationNone;
986 nsresult = NSDragOperationLink;
988 nsresult = NSDragOperationMove;
990 nsresult = NSDragOperationCopy;
997 void wxWidgetCocoaImpl::draggingExited(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
999 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1000 NSPasteboard *pboard = [sender draggingPasteboard];
1002 wxWindow* wxpeer = GetWXPeer();
1003 if ( wxpeer == NULL )
1006 wxDropTarget* target = wxpeer->GetDropTarget();
1007 if ( target == NULL )
1010 PasteboardRef pboardRef;
1011 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1012 target->SetCurrentDragPasteboard(pboardRef);
1014 CFRelease(pboardRef);
1017 unsigned int wxWidgetCocoaImpl::draggingUpdated(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1019 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1020 NSPasteboard *pboard = [sender draggingPasteboard];
1021 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1023 wxWindow* wxpeer = GetWXPeer();
1024 if ( wxpeer == NULL )
1025 return NSDragOperationNone;
1027 wxDropTarget* target = wxpeer->GetDropTarget();
1028 if ( target == NULL )
1029 return NSDragOperationNone;
1031 wxDragResult result = wxDragNone;
1032 NSPoint nspoint = [m_osxView convertPoint:[sender draggingLocation] fromView:nil];
1033 wxPoint pt = wxFromNSPoint( m_osxView, nspoint );
1035 if ( sourceDragMask & NSDragOperationLink )
1036 result = wxDragLink;
1037 else if ( sourceDragMask & NSDragOperationCopy )
1038 result = wxDragCopy;
1039 else if ( sourceDragMask & NSDragOperationMove )
1040 result = wxDragMove;
1042 PasteboardRef pboardRef;
1043 PasteboardCreate((CFStringRef)[pboard name], &pboardRef);
1044 target->SetCurrentDragPasteboard(pboardRef);
1045 result = target->OnDragOver(pt.x, pt.y, result);
1046 CFRelease(pboardRef);
1048 NSDragOperation nsresult = NSDragOperationNone;
1052 nsresult = NSDragOperationLink;
1054 nsresult = NSDragOperationMove;
1056 nsresult = NSDragOperationCopy;
1063 bool wxWidgetCocoaImpl::performDragOperation(void* s, WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1065 id <NSDraggingInfo>sender = (id <NSDraggingInfo>) s;
1067 NSPasteboard *pboard = [sender draggingPasteboard];
1068 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1070 wxWindow* wxpeer = GetWXPeer();
1071 wxDropTarget* target = wxpeer->GetDropTarget();
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);
1087 if (target->OnDrop(pt.x, pt.y))
1088 result = target->OnData(pt.x, pt.y, result);
1090 CFRelease(pboardRef);
1092 return result != wxDragNone;
1095 typedef void (*wxOSX_TextEventHandlerPtr)(NSView* self, SEL _cmd, NSString *event);
1096 typedef void (*wxOSX_EventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
1097 typedef BOOL (*wxOSX_PerformKeyEventHandlerPtr)(NSView* self, SEL _cmd, NSEvent *event);
1098 typedef BOOL (*wxOSX_FocusHandlerPtr)(NSView* self, SEL _cmd);
1099 typedef BOOL (*wxOSX_ResetCursorRectsHandlerPtr)(NSView* self, SEL _cmd);
1101 void wxWidgetCocoaImpl::mouseEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1103 if ( !DoHandleMouseEvent(event) )
1105 // for plain NSView mouse events would propagate to parents otherwise
1108 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1109 superimpl(slf, (SEL)_cmd, event);
1111 // super of built-ins keeps the mouse up, as wx expects this event, we have to synthesize it
1113 if ( [ event type] == NSLeftMouseDown )
1115 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
1116 SetupMouseEvent(wxevent , event) ;
1117 wxevent.SetEventType(wxEVT_LEFT_UP);
1119 GetWXPeer()->HandleWindowEvent(wxevent);
1125 void wxWidgetCocoaImpl::keyEvent(WX_NSEvent event, WXWidget slf, void *_cmd)
1127 if ( [event type] == NSKeyDown )
1129 // there are key equivalents that are not command-combos and therefore not handled by cocoa automatically,
1130 // therefore we call the menubar directly here, exit if the menu is handling the shortcut
1131 if ( [[[NSApplication sharedApplication] mainMenu] performKeyEquivalent:event] )
1134 m_lastKeyDownEvent = event;
1137 if ( GetFocusedViewInWindow([slf window]) != slf || m_hasEditor || !DoHandleKeyEvent(event) )
1139 wxOSX_EventHandlerPtr superimpl = (wxOSX_EventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1140 superimpl(slf, (SEL)_cmd, event);
1142 m_lastKeyDownEvent = NULL;
1145 void wxWidgetCocoaImpl::insertText(NSString* text, WXWidget slf, void *_cmd)
1147 if ( m_lastKeyDownEvent==NULL || m_hasEditor || !DoHandleCharEvent(m_lastKeyDownEvent, text) )
1149 wxOSX_TextEventHandlerPtr superimpl = (wxOSX_TextEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1150 superimpl(slf, (SEL)_cmd, text);
1155 bool wxWidgetCocoaImpl::performKeyEquivalent(WX_NSEvent event, WXWidget slf, void *_cmd)
1157 bool handled = false;
1159 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
1160 SetupKeyEvent( wxevent, event );
1162 // because performKeyEquivalent is going up the entire view hierarchy, we don't have to
1163 // walk up the ancestors ourselves but let cocoa do it
1165 int command = m_wxPeer->GetAcceleratorTable()->GetCommand( wxevent );
1168 wxEvtHandler * const handler = m_wxPeer->GetEventHandler();
1170 wxCommandEvent command_event( wxEVT_COMMAND_MENU_SELECTED, command );
1171 command_event.SetEventObject( wxevent.GetEventObject() );
1172 handled = handler->ProcessEvent( command_event );
1176 // accelerators can also be used with buttons, try them too
1177 command_event.SetEventType(wxEVT_COMMAND_BUTTON_CLICKED);
1178 handled = handler->ProcessEvent( command_event );
1184 wxOSX_PerformKeyEventHandlerPtr superimpl = (wxOSX_PerformKeyEventHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1185 return superimpl(slf, (SEL)_cmd, event);
1190 bool wxWidgetCocoaImpl::acceptsFirstResponder(WXWidget slf, void *_cmd)
1193 return m_wxPeer->AcceptsFocus();
1196 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1197 return superimpl(slf, (SEL)_cmd);
1201 bool wxWidgetCocoaImpl::becomeFirstResponder(WXWidget slf, void *_cmd)
1203 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1204 // get the current focus before running becomeFirstResponder
1205 NSView* otherView = FindFocus();
1207 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1208 BOOL r = superimpl(slf, (SEL)_cmd);
1211 DoNotifyFocusEvent( true, otherWindow );
1217 bool wxWidgetCocoaImpl::resignFirstResponder(WXWidget slf, void *_cmd)
1219 wxOSX_FocusHandlerPtr superimpl = (wxOSX_FocusHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1220 BOOL r = superimpl(slf, (SEL)_cmd);
1221 // get the current focus after running resignFirstResponder
1222 // note that this value isn't reliable, it might return the same view that
1224 NSView* otherView = FindFocus();
1225 wxWidgetImpl* otherWindow = FindFromWXWidget(otherView);
1227 // It doesn't make sense to notify about the loss of focus if we're not
1228 // really losing it and the window which has just gained focus is the same
1229 // one as this window itself. Of course, this should never happen in the
1230 // first place but somehow it does in wxGrid code and without this check we
1231 // enter into an infinite recursion, see #12267.
1232 if ( otherWindow == this )
1235 // NSTextViews have an editor as true responder, therefore the might get the
1236 // resign notification if their editor takes over, don't trigger any event then
1237 if ( r && !m_hasEditor)
1239 DoNotifyFocusEvent( false, otherWindow );
1244 void wxWidgetCocoaImpl::resetCursorRects(WXWidget slf, void *_cmd)
1246 wxWindow* wxpeer = GetWXPeer();
1249 NSCursor *cursor = (NSCursor*)wxpeer->GetCursor().GetHCURSOR();
1252 wxOSX_ResetCursorRectsHandlerPtr superimpl = (wxOSX_ResetCursorRectsHandlerPtr) [[slf superclass] instanceMethodForSelector:(SEL)_cmd];
1253 superimpl(slf, (SEL)_cmd);
1257 [slf addCursorRect: [slf bounds]
1263 bool wxWidgetCocoaImpl::isFlipped(WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd))
1269 #define OSX_DEBUG_DRAWING 0
1271 void wxWidgetCocoaImpl::drawRect(void* rect, WXWidget slf, void *WXUNUSED(_cmd))
1273 // preparing the update region
1276 const NSRect *rects;
1279 [slf getRectsBeingDrawn:&rects count:&count];
1280 for ( int i = 0 ; i < count ; ++i )
1282 updateRgn.Union(wxFromNSRect(slf, rects[i]));
1285 wxWindow* wxpeer = GetWXPeer();
1287 if ( wxpeer->MacGetLeftBorderSize() != 0 || wxpeer->MacGetTopBorderSize() != 0 )
1289 // as this update region is in native window locals we must adapt it to wx window local
1290 updateRgn.Offset( wxpeer->MacGetLeftBorderSize() , wxpeer->MacGetTopBorderSize() );
1293 // Restrict the update region to the shape of the window, if any, and also
1294 // remember the region that we need to clear later.
1295 wxNonOwnedWindow* const tlwParent = wxpeer->MacGetTopLevelWindow();
1296 const bool isTopLevel = tlwParent == wxpeer;
1298 if ( tlwParent->GetWindowStyle() & wxFRAME_SHAPED )
1301 clearRgn = updateRgn;
1303 int xoffset = 0, yoffset = 0;
1304 wxRegion rgn = tlwParent->GetShape();
1305 wxpeer->MacRootWindowToWindow( &xoffset, &yoffset );
1306 rgn.Offset( xoffset, yoffset );
1307 updateRgn.Intersect(rgn);
1311 // Exclude the window shape from the region to be cleared below.
1312 rgn.Xor(wxpeer->GetSize());
1313 clearRgn.Intersect(rgn);
1317 wxpeer->GetUpdateRegion() = updateRgn;
1319 // setting up the drawing context
1321 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1322 CGContextSaveGState( context );
1324 #if OSX_DEBUG_DRAWING
1325 CGContextBeginPath( context );
1326 CGContextMoveToPoint(context, 0, 0);
1327 NSRect bounds = [slf bounds];
1328 CGContextAddLineToPoint(context, 10, 0);
1329 CGContextMoveToPoint(context, 0, 0);
1330 CGContextAddLineToPoint(context, 0, 10);
1331 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1332 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
1333 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
1334 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
1335 CGContextClosePath( context );
1336 CGContextStrokePath(context);
1341 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1342 CGContextScaleCTM( context, 1, -1 );
1345 wxpeer->MacSetCGContextRef( context );
1347 bool handled = wxpeer->MacDoRedraw( 0 );
1348 CGContextRestoreGState( context );
1350 CGContextSaveGState( context );
1354 SEL _cmd = @selector(drawRect:);
1355 wxOSX_DrawRectHandlerPtr superimpl = (wxOSX_DrawRectHandlerPtr) [[slf superclass] instanceMethodForSelector:_cmd];
1356 superimpl(slf, _cmd, *(NSRect*)rect);
1357 CGContextRestoreGState( context );
1358 CGContextSaveGState( context );
1360 // as we called restore above, we have to flip again if necessary
1363 CGContextTranslateCTM( context, 0, [m_osxView bounds].size.height );
1364 CGContextScaleCTM( context, 1, -1 );
1369 // We also need to explicitly draw the part of the top level window
1370 // outside of its region with transparent colour to ensure that it is
1371 // really transparent.
1372 if ( clearRgn.IsOk() )
1374 wxMacCGContextStateSaver saveState(context);
1375 wxWindowDC dc(wxpeer);
1376 dc.SetBackground(wxBrush(wxTransparentColour));
1377 dc.SetDeviceClippingRegion(clearRgn);
1381 #if wxUSE_GRAPHICS_CONTEXT
1382 // If the window shape is defined by a path, stroke the path to show
1383 // the window border.
1384 const wxGraphicsPath& path = tlwParent->GetShapePath();
1385 if ( !path.IsNull() )
1387 CGContextSetLineWidth(context, 1);
1388 CGContextSetStrokeColorWithColor(context, wxLIGHT_GREY->GetCGColor());
1389 CGContextAddPath(context, (CGPathRef) path.GetNativePath());
1390 CGContextStrokePath(context);
1392 #endif // wxUSE_GRAPHICS_CONTEXT
1395 wxpeer->MacPaintChildrenBorders();
1396 wxpeer->MacSetCGContextRef( NULL );
1397 CGContextRestoreGState( context );
1400 void wxWidgetCocoaImpl::controlAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1402 wxWindow* wxpeer = (wxWindow*) GetWXPeer();
1404 wxpeer->OSXHandleClicked(0);
1407 void wxWidgetCocoaImpl::controlDoubleAction( WXWidget WXUNUSED(slf), void *WXUNUSED(_cmd), void *WXUNUSED(sender))
1411 void wxWidgetCocoaImpl::controlTextDidChange()
1413 wxWindow* wxpeer = (wxWindow*)GetWXPeer();
1416 // since native rtti doesn't have to be enabled and wx' rtti is not aware of the mixin wxTextEntry, workaround is needed
1417 wxTextCtrl *tc = wxDynamicCast( wxpeer , wxTextCtrl );
1418 wxComboBox *cb = wxDynamicCast( wxpeer , wxComboBox );
1420 tc->SendTextUpdatedEventIfAllowed();
1422 cb->SendTextUpdatedEventIfAllowed();
1425 wxFAIL_MSG("Unexpected class for controlTextDidChange event");
1432 #if OBJC_API_VERSION >= 2
1434 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1435 class_addMethod(c, s, i, t );
1439 #define wxOSX_CLASS_ADD_METHOD( c, s, i, t ) \
1440 { s, (char*) t, i },
1444 void wxOSXCocoaClassAddWXMethods(Class c)
1447 #if OBJC_API_VERSION < 2
1448 static objc_method wxmethods[] =
1452 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1453 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1454 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDown:), (IMP) wxOSX_mouseEvent, "v@:@" )
1456 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1457 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1458 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseUp:), (IMP) wxOSX_mouseEvent, "v@:@" )
1460 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseMoved:), (IMP) wxOSX_mouseEvent, "v@:@" )
1462 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1463 wxOSX_CLASS_ADD_METHOD(c, @selector(rightMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1464 wxOSX_CLASS_ADD_METHOD(c, @selector(otherMouseDragged:), (IMP) wxOSX_mouseEvent, "v@:@" )
1466 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstMouse:), (IMP) wxOSX_acceptsFirstMouse, "v@:@" )
1468 wxOSX_CLASS_ADD_METHOD(c, @selector(scrollWheel:), (IMP) wxOSX_mouseEvent, "v@:@" )
1469 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseEntered:), (IMP) wxOSX_mouseEvent, "v@:@" )
1470 wxOSX_CLASS_ADD_METHOD(c, @selector(mouseExited:), (IMP) wxOSX_mouseEvent, "v@:@" )
1472 wxOSX_CLASS_ADD_METHOD(c, @selector(keyDown:), (IMP) wxOSX_keyEvent, "v@:@" )
1473 wxOSX_CLASS_ADD_METHOD(c, @selector(keyUp:), (IMP) wxOSX_keyEvent, "v@:@" )
1474 wxOSX_CLASS_ADD_METHOD(c, @selector(flagsChanged:), (IMP) wxOSX_keyEvent, "v@:@" )
1476 wxOSX_CLASS_ADD_METHOD(c, @selector(insertText:), (IMP) wxOSX_insertText, "v@:@" )
1478 wxOSX_CLASS_ADD_METHOD(c, @selector(performKeyEquivalent:), (IMP) wxOSX_performKeyEquivalent, "c@:@" )
1480 wxOSX_CLASS_ADD_METHOD(c, @selector(acceptsFirstResponder), (IMP) wxOSX_acceptsFirstResponder, "c@:" )
1481 wxOSX_CLASS_ADD_METHOD(c, @selector(becomeFirstResponder), (IMP) wxOSX_becomeFirstResponder, "c@:" )
1482 wxOSX_CLASS_ADD_METHOD(c, @selector(resignFirstResponder), (IMP) wxOSX_resignFirstResponder, "c@:" )
1483 wxOSX_CLASS_ADD_METHOD(c, @selector(resetCursorRects), (IMP) wxOSX_resetCursorRects, "v@:" )
1485 wxOSX_CLASS_ADD_METHOD(c, @selector(isFlipped), (IMP) wxOSX_isFlipped, "c@:" )
1486 wxOSX_CLASS_ADD_METHOD(c, @selector(drawRect:), (IMP) wxOSX_drawRect, "v@:{_NSRect={_NSPoint=ff}{_NSSize=ff}}" )
1488 wxOSX_CLASS_ADD_METHOD(c, @selector(controlAction:), (IMP) wxOSX_controlAction, "v@:@" )
1489 wxOSX_CLASS_ADD_METHOD(c, @selector(controlDoubleAction:), (IMP) wxOSX_controlDoubleAction, "v@:@" )
1491 #if wxUSE_DRAG_AND_DROP
1492 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingEntered:), (IMP) wxOSX_draggingEntered, "I@:@" )
1493 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingUpdated:), (IMP) wxOSX_draggingUpdated, "I@:@" )
1494 wxOSX_CLASS_ADD_METHOD(c, @selector(draggingExited:), (IMP) wxOSX_draggingExited, "v@:@" )
1495 wxOSX_CLASS_ADD_METHOD(c, @selector(performDragOperation:), (IMP) wxOSX_performDragOperation, "c@:@" )
1498 #if OBJC_API_VERSION < 2
1500 static int method_count = WXSIZEOF( wxmethods );
1501 static objc_method_list *wxmethodlist = NULL;
1502 if ( wxmethodlist == NULL )
1504 wxmethodlist = (objc_method_list*) malloc(sizeof(objc_method_list) + sizeof(wxmethods) );
1505 memcpy( &wxmethodlist->method_list[0], &wxmethods[0], sizeof(wxmethods) );
1506 wxmethodlist->method_count = method_count;
1507 wxmethodlist->obsolete = 0;
1509 class_addMethods( c, wxmethodlist );
1514 // C++ implementation class
1517 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
1519 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl, bool isUserPane ) :
1520 wxWidgetImpl( peer, isRootControl, isUserPane )
1525 // check if the user wants to create the control initially hidden
1526 if ( !peer->IsShown() )
1527 SetVisibility(false);
1529 // gc aware handling
1531 CFRetain(m_osxView);
1532 [m_osxView release];
1535 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
1540 void wxWidgetCocoaImpl::Init()
1544 m_lastKeyDownEvent = NULL;
1545 m_hasEditor = false;
1548 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
1550 RemoveAssociations( this );
1552 if ( !IsRootControl() )
1554 NSView *sv = [m_osxView superview];
1556 [m_osxView removeFromSuperview];
1558 // gc aware handling
1560 CFRelease(m_osxView);
1563 bool wxWidgetCocoaImpl::IsVisible() const
1565 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
1568 void wxWidgetCocoaImpl::SetVisibility( bool visible )
1570 [m_osxView setHidden:(visible ? NO:YES)];
1573 // ----------------------------------------------------------------------------
1574 // window animation stuff
1575 // ----------------------------------------------------------------------------
1577 // define a delegate used to refresh the window during animation
1578 @interface wxNSAnimationDelegate : NSObject wxOSX_10_6_AND_LATER(<NSAnimationDelegate>)
1584 - (id)init:(wxWindow *)win;
1588 // NSAnimationDelegate methods
1589 - (void)animationDidEnd:(NSAnimation*)animation;
1590 - (void)animation:(NSAnimation*)animation
1591 didReachProgressMark:(NSAnimationProgress)progress;
1594 @implementation wxNSAnimationDelegate
1596 - (id)init:(wxWindow *)win
1598 self = [super init];
1611 - (void)animation:(NSAnimation*)animation
1612 didReachProgressMark:(NSAnimationProgress)progress
1614 wxUnusedVar(animation);
1615 wxUnusedVar(progress);
1617 m_win->SendSizeEvent();
1618 m_win->MacOnInternalSize();
1621 - (void)animationDidEnd:(NSAnimation*)animation
1623 wxUnusedVar(animation);
1631 wxWidgetCocoaImpl::ShowViewOrWindowWithEffect(wxWindow *win,
1633 wxShowEffect effect,
1636 // create the dictionary describing the animation to perform on this view
1638 viewOrWin = static_cast<NSObject *>(win->OSXGetViewOrWindow());
1639 NSMutableDictionary * const
1640 dict = [NSMutableDictionary dictionaryWithCapacity:4];
1641 [dict setObject:viewOrWin forKey:NSViewAnimationTargetKey];
1643 // determine the start and end rectangles assuming we're hiding the window
1644 const wxRect rectOrig = win->GetRect();
1652 if ( effect == wxSHOW_EFFECT_ROLL_TO_LEFT ||
1653 effect == wxSHOW_EFFECT_SLIDE_TO_LEFT )
1654 effect = wxSHOW_EFFECT_ROLL_TO_RIGHT;
1655 else if ( effect == wxSHOW_EFFECT_ROLL_TO_RIGHT ||
1656 effect == wxSHOW_EFFECT_SLIDE_TO_RIGHT )
1657 effect = wxSHOW_EFFECT_ROLL_TO_LEFT;
1658 else if ( effect == wxSHOW_EFFECT_ROLL_TO_TOP ||
1659 effect == wxSHOW_EFFECT_SLIDE_TO_TOP )
1660 effect = wxSHOW_EFFECT_ROLL_TO_BOTTOM;
1661 else if ( effect == wxSHOW_EFFECT_ROLL_TO_BOTTOM ||
1662 effect == wxSHOW_EFFECT_SLIDE_TO_BOTTOM )
1663 effect = wxSHOW_EFFECT_ROLL_TO_TOP;
1668 case wxSHOW_EFFECT_ROLL_TO_LEFT:
1669 case wxSHOW_EFFECT_SLIDE_TO_LEFT:
1673 case wxSHOW_EFFECT_ROLL_TO_RIGHT:
1674 case wxSHOW_EFFECT_SLIDE_TO_RIGHT:
1675 rectEnd.x = rectStart.GetRight();
1679 case wxSHOW_EFFECT_ROLL_TO_TOP:
1680 case wxSHOW_EFFECT_SLIDE_TO_TOP:
1684 case wxSHOW_EFFECT_ROLL_TO_BOTTOM:
1685 case wxSHOW_EFFECT_SLIDE_TO_BOTTOM:
1686 rectEnd.y = rectStart.GetBottom();
1690 case wxSHOW_EFFECT_EXPAND:
1691 rectEnd.x = rectStart.x + rectStart.width / 2;
1692 rectEnd.y = rectStart.y + rectStart.height / 2;
1697 case wxSHOW_EFFECT_BLEND:
1698 [dict setObject:(show ? NSViewAnimationFadeInEffect
1699 : NSViewAnimationFadeOutEffect)
1700 forKey:NSViewAnimationEffectKey];
1703 case wxSHOW_EFFECT_NONE:
1704 case wxSHOW_EFFECT_MAX:
1705 wxFAIL_MSG( "unexpected animation effect" );
1709 wxFAIL_MSG( "unknown animation effect" );
1715 // we need to restore it to the original rectangle instead of making it
1717 wxSwap(rectStart, rectEnd);
1719 // and as the window is currently hidden, we need to show it for the
1720 // animation to be visible at all (but don't restore it at its full
1721 // rectangle as it shouldn't appear immediately)
1722 win->SetSize(rectStart);
1726 NSView * const parentView = [viewOrWin isKindOfClass:[NSView class]]
1727 ? [(NSView *)viewOrWin superview]
1729 const NSRect rStart = wxToNSRect(parentView, rectStart);
1730 const NSRect rEnd = wxToNSRect(parentView, rectEnd);
1732 [dict setObject:[NSValue valueWithRect:rStart]
1733 forKey:NSViewAnimationStartFrameKey];
1734 [dict setObject:[NSValue valueWithRect:rEnd]
1735 forKey:NSViewAnimationEndFrameKey];
1737 // create an animation using the values in the above dictionary
1738 NSViewAnimation * const
1739 anim = [[NSViewAnimation alloc]
1740 initWithViewAnimations:[NSArray arrayWithObject:dict]];
1744 // what is a good default duration? Windows uses 200ms, Web frameworks
1745 // use anything from 250ms to 1s... choose something in the middle
1749 [anim setDuration:timeout/1000.]; // duration is in seconds here
1751 // if the window being animated changes its layout depending on its size
1752 // (which is almost always the case) we need to redo it during animation
1754 // the number of layouts here is arbitrary, but 10 seems like too few (e.g.
1755 // controls in wxInfoBar visibly jump around)
1756 const int NUM_LAYOUTS = 20;
1757 for ( float f = 1./NUM_LAYOUTS; f < 1.; f += 1./NUM_LAYOUTS )
1758 [anim addProgressMark:f];
1760 wxNSAnimationDelegate * const
1761 animDelegate = [[wxNSAnimationDelegate alloc] init:win];
1762 [anim setDelegate:animDelegate];
1763 [anim startAnimation];
1765 // Cocoa is capable of doing animation asynchronously or even from separate
1766 // thread but wx API doesn't provide any way to be notified about the
1767 // animation end and without this we really must ensure that the window has
1768 // the expected (i.e. the same as if a simple Show() had been used) size
1769 // when we return, so block here until the animation finishes
1771 // notice that because the default animation mode is NSAnimationBlocking,
1772 // no user input events ought to be processed from here
1774 wxEventLoopGuarantor ensureEventLoopExistence;
1775 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1776 while ( ![animDelegate isDone] )
1782 // NSViewAnimation is smart enough to hide the NSView being animated at
1783 // the end but we also must ensure that it's hidden for wx too
1786 // and we must also restore its size because it isn't expected to
1787 // change just because the window was hidden
1788 win->SetSize(rectOrig);
1792 // refresh it once again after the end to ensure that everything is in
1794 win->SendSizeEvent();
1795 win->MacOnInternalSize();
1798 [anim setDelegate:nil];
1799 [animDelegate release];
1805 bool wxWidgetCocoaImpl::ShowWithEffect(bool show,
1806 wxShowEffect effect,
1809 return ShowViewOrWindowWithEffect(m_wxPeer, show, effect, timeout);
1812 /* note that the drawing order between siblings is not defined under 10.4 */
1813 /* only starting from 10.5 the subview order is respected */
1815 /* NSComparisonResult is typedef'd as an enum pre-Leopard but typedef'd as
1816 * NSInteger post-Leopard. Pre-Leopard the Cocoa toolkit expects a function
1817 * returning int and not NSComparisonResult. Post-Leopard the Cocoa toolkit
1818 * expects a function returning the new non-enum NSComparsionResult.
1819 * Hence we create a typedef named CocoaWindowCompareFunctionResult.
1821 #if defined(NSINTEGER_DEFINED)
1822 typedef NSComparisonResult CocoaWindowCompareFunctionResult;
1824 typedef int CocoaWindowCompareFunctionResult;
1827 class CocoaWindowCompareContext
1829 wxDECLARE_NO_COPY_CLASS(CocoaWindowCompareContext);
1831 CocoaWindowCompareContext(); // Not implemented
1832 CocoaWindowCompareContext(NSView *target, NSArray *subviews)
1835 // Cocoa sorts subviews in-place.. make a copy
1836 m_subviews = [subviews copy];
1839 ~CocoaWindowCompareContext()
1840 { // release the copy
1841 [m_subviews release];
1844 { return m_target; }
1847 { return m_subviews; }
1849 /* Helper function that returns the comparison based off of the original ordering */
1850 CocoaWindowCompareFunctionResult CompareUsingOriginalOrdering(id first, id second)
1852 NSUInteger firstI = [m_subviews indexOfObjectIdenticalTo:first];
1853 NSUInteger secondI = [m_subviews indexOfObjectIdenticalTo:second];
1854 // NOTE: If either firstI or secondI is NSNotFound then it will be NSIntegerMax and thus will
1855 // likely compare higher than the other view which is reasonable considering the only way that
1856 // can happen is if the subview was added after our call to subviews but before the call to
1857 // sortSubviewsUsingFunction:context:. Thus we don't bother checking. Particularly because
1858 // that case should never occur anyway because that would imply a multi-threaded GUI call
1859 // which is a big no-no with Cocoa.
1861 // Subviews are ordered from back to front meaning one that is already lower will have an lower index.
1862 NSComparisonResult result = (firstI < secondI)
1863 ? NSOrderedAscending /* -1 */
1864 : (firstI > secondI)
1865 ? NSOrderedDescending /* 1 */
1866 : NSOrderedSame /* 0 */;
1871 /* The subview we are trying to Raise or Lower */
1873 /* A copy of the original array of subviews */
1874 NSArray *m_subviews;
1877 /* Causes Cocoa to raise the target view to the top of the Z-Order by telling the sort function that
1878 * the target view is always higher than every other view. When comparing two views neither of
1879 * which is the target, it returns the correct response based on the original ordering
1881 static CocoaWindowCompareFunctionResult CocoaRaiseWindowCompareFunction(id first, id second, void *ctx)
1883 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
1884 // first should be ordered higher
1885 if(first==compareContext->target())
1886 return NSOrderedDescending;
1887 // second should be ordered higher
1888 if(second==compareContext->target())
1889 return NSOrderedAscending;
1890 return compareContext->CompareUsingOriginalOrdering(first,second);
1893 void wxWidgetCocoaImpl::Raise()
1895 NSView* nsview = m_osxView;
1897 NSView *superview = [nsview superview];
1898 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
1900 [superview sortSubviewsUsingFunction:
1901 CocoaRaiseWindowCompareFunction
1902 context: &compareContext];
1906 /* Causes Cocoa to lower the target view to the bottom of the Z-Order by telling the sort function that
1907 * the target view is always lower than every other view. When comparing two views neither of
1908 * which is the target, it returns the correct response based on the original ordering
1910 static CocoaWindowCompareFunctionResult CocoaLowerWindowCompareFunction(id first, id second, void *ctx)
1912 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
1913 // first should be ordered lower
1914 if(first==compareContext->target())
1915 return NSOrderedAscending;
1916 // second should be ordered lower
1917 if(second==compareContext->target())
1918 return NSOrderedDescending;
1919 return compareContext->CompareUsingOriginalOrdering(first,second);
1922 void wxWidgetCocoaImpl::Lower()
1924 NSView* nsview = m_osxView;
1926 NSView *superview = [nsview superview];
1927 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
1929 [superview sortSubviewsUsingFunction:
1930 CocoaLowerWindowCompareFunction
1931 context: &compareContext];
1934 void wxWidgetCocoaImpl::ScrollRect( const wxRect *WXUNUSED(rect), int WXUNUSED(dx), int WXUNUSED(dy) )
1939 // We should do something like this, but it wasn't working in 10.4.
1940 if (GetNeedsDisplay() )
1944 NSRect r = wxToNSRect( [m_osxView superview], *rect );
1945 NSSize offset = NSMakeSize((float)dx, (float)dy);
1946 [m_osxView scrollRect:r by:offset];
1950 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
1952 wxWindowMac* parent = GetWXPeer()->GetParent();
1953 // under Cocoa we might have a contentView in the wxParent to which we have to
1954 // adjust the coordinates
1955 if (parent && [m_osxView superview] != parent->GetHandle() )
1957 int cx = 0,cy = 0,cw = 0,ch = 0;
1958 if ( parent->GetPeer() )
1960 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
1965 [[m_osxView superview] setNeedsDisplayInRect:[m_osxView frame]];
1966 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
1967 [m_osxView setFrame:r];
1968 [[m_osxView superview] setNeedsDisplayInRect:r];
1970 wxNSView* wxview = (wxNSView*)m_osxView;
1971 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
1972 if ([wxview respondsToSelector:@selector(updateTrackingArea)] )
1973 [wxview updateTrackingArea];
1975 if ([m_osxView respondsToSelector:@selector(trackingTag)] )
1977 if ( [wxview trackingTag] )
1978 [wxview removeTrackingRect: [wxview trackingTag]];
1980 [wxview setTrackingTag: [wxview addTrackingRect: [m_osxView bounds] owner: wxview userData: nil assumeInside: NO]];
1985 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
1987 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
1991 // under Cocoa we might have a contentView in the wxParent to which we have to
1992 // adjust the coordinates
1993 wxWindowMac* parent = GetWXPeer()->GetParent();
1994 if (parent && [m_osxView superview] != parent->GetHandle() )
1996 int cx = 0,cy = 0,cw = 0,ch = 0;
1997 if ( parent->GetPeer() )
1999 parent->GetPeer()->GetContentArea(cx, cy, cw, ch);
2006 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
2008 NSRect rect = [m_osxView frame];
2009 width = (int)rect.size.width;
2010 height = (int)rect.size.height;
2013 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
2015 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
2017 NSView* cv = [m_osxView contentView];
2019 NSRect bounds = [m_osxView bounds];
2020 NSRect rect = [cv frame];
2022 int y = (int)rect.origin.y;
2023 int x = (int)rect.origin.x;
2024 if ( ![ m_osxView isFlipped ] )
2025 y = (int)(bounds.size.height - (rect.origin.y + rect.size.height));
2028 width = (int)rect.size.width;
2029 height = (int)rect.size.height;
2034 GetSize( width, height );
2038 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
2041 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
2043 [m_osxView setNeedsDisplay:YES];
2046 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
2048 return [m_osxView needsDisplay];
2051 bool wxWidgetCocoaImpl::CanFocus() const
2053 return [m_osxView canBecomeKeyView] == YES;
2056 bool wxWidgetCocoaImpl::HasFocus() const
2058 return ( FindFocus() == m_osxView );
2061 bool wxWidgetCocoaImpl::SetFocus()
2066 // TODO remove if no issues arise: should not raise the window, only assign focus
2067 //[[m_osxView window] makeKeyAndOrderFront:nil] ;
2068 [[m_osxView window] makeFirstResponder: m_osxView] ;
2073 void wxWidgetCocoaImpl::RemoveFromParent()
2075 [m_osxView removeFromSuperview];
2078 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
2080 NSView* container = parent->GetWXWidget() ;
2081 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
2082 [container addSubview:m_osxView];
2085 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &col )
2087 NSView* targetView = m_osxView;
2088 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2089 targetView = [(NSScrollView*) m_osxView documentView];
2091 if ( [targetView respondsToSelector:@selector(setBackgroundColor:) ] )
2093 [targetView setBackgroundColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2094 green:(CGFloat) (col.Green() / 255.0)
2095 blue:(CGFloat) (col.Blue() / 255.0)
2096 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2100 bool wxWidgetCocoaImpl::SetBackgroundStyle( wxBackgroundStyle style )
2102 BOOL opaque = ( style == wxBG_STYLE_PAINT );
2104 if ( [m_osxView respondsToSelector:@selector(setOpaque:) ] )
2106 [m_osxView setOpaque: opaque];
2112 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
2114 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
2116 wxCFStringRef cf( title , encoding );
2117 [m_osxView setTitle:cf.AsNSString()];
2119 else if ( [m_osxView respondsToSelector:@selector(setStringValue:) ] )
2121 wxCFStringRef cf( title , encoding );
2122 [m_osxView setStringValue:cf.AsNSString()];
2127 void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
2129 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
2130 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
2131 *pt = wxFromNSPoint( to->GetWXWidget(), p );
2134 wxInt32 wxWidgetCocoaImpl::GetValue() const
2136 return [(NSControl*)m_osxView intValue];
2139 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
2141 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
2143 [m_osxView setIntValue:v];
2145 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
2147 [m_osxView setFloatValue:(double)v];
2149 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
2151 [m_osxView setDoubleValue:(double)v];
2155 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
2157 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
2159 [m_osxView setMinValue:(double)v];
2163 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
2165 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
2167 [m_osxView setMaxValue:(double)v];
2171 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
2173 if ( [m_osxView respondsToSelector:@selector(minValue)] )
2175 return (int)[m_osxView minValue];
2180 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
2182 if ( [m_osxView respondsToSelector:@selector(maxValue)] )
2184 return (int)[m_osxView maxValue];
2189 wxBitmap wxWidgetCocoaImpl::GetBitmap() const
2193 // TODO: how to create a wxBitmap from NSImage?
2195 if ( [m_osxView respondsToSelector:@selector(image:)] )
2196 bmp = [m_osxView image];
2202 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
2204 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
2207 [m_osxView setImage:bitmap.GetNSImage()];
2209 [m_osxView setImage:nil];
2211 [m_osxView setNeedsDisplay:YES];
2215 void wxWidgetCocoaImpl::SetBitmapPosition( wxDirection dir )
2217 if ( [m_osxView respondsToSelector:@selector(setImagePosition:)] )
2219 NSCellImagePosition pos;
2239 wxFAIL_MSG( "invalid image position" );
2243 [m_osxView setImagePosition:pos];
2247 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& WXUNUSED(notebook))
2249 // implementation in subclass
2252 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
2254 r->x = r->y = r->width = r->height = 0;
2256 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
2258 NSRect former = [m_osxView frame];
2259 [m_osxView sizeToFit];
2260 NSRect best = [m_osxView frame];
2261 [m_osxView setFrame:former];
2262 r->width = (int)best.size.width;
2263 r->height = (int)best.size.height;
2267 bool wxWidgetCocoaImpl::IsEnabled() const
2269 NSView* targetView = m_osxView;
2270 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2271 targetView = [(NSScrollView*) m_osxView documentView];
2273 if ( [targetView respondsToSelector:@selector(isEnabled) ] )
2274 return [targetView isEnabled];
2278 void wxWidgetCocoaImpl::Enable( bool enable )
2280 NSView* targetView = m_osxView;
2281 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2282 targetView = [(NSScrollView*) m_osxView documentView];
2284 if ( [targetView respondsToSelector:@selector(setEnabled:) ] )
2285 [targetView setEnabled:enable];
2288 void wxWidgetCocoaImpl::PulseGauge()
2292 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 WXUNUSED(val), wxInt32 WXUNUSED(view) )
2296 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
2298 NSControlSize size = NSRegularControlSize;
2302 case wxWINDOW_VARIANT_NORMAL :
2303 size = NSRegularControlSize;
2306 case wxWINDOW_VARIANT_SMALL :
2307 size = NSSmallControlSize;
2310 case wxWINDOW_VARIANT_MINI :
2311 size = NSMiniControlSize;
2314 case wxWINDOW_VARIANT_LARGE :
2315 size = NSRegularControlSize;
2319 wxFAIL_MSG(wxT("unexpected window variant"));
2322 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
2323 [m_osxView setControlSize:size];
2324 else if ([m_osxView respondsToSelector:@selector(cell)])
2326 id cell = [(id)m_osxView cell];
2327 if ([cell respondsToSelector:@selector(setControlSize:)])
2328 [cell setControlSize:size];
2332 void wxWidgetCocoaImpl::SetFont(wxFont const& font, wxColour const&col, long, bool)
2334 if ([m_osxView respondsToSelector:@selector(setFont:)])
2335 [m_osxView setFont: font.OSXGetNSFont()];
2336 if ([m_osxView respondsToSelector:@selector(setTextColor:)])
2337 [m_osxView setTextColor:[NSColor colorWithCalibratedRed:(CGFloat) (col.Red() / 255.0)
2338 green:(CGFloat) (col.Green() / 255.0)
2339 blue:(CGFloat) (col.Blue() / 255.0)
2340 alpha:(CGFloat) (col.Alpha() / 255.0)]];
2343 NSToolTipTag tt = 0;
2345 void wxWidgetCocoaImpl::SetToolTip(wxToolTip* tooltip)
2352 [m_osxView removeToolTip:tt];
2356 wxCFStringRef cf( tooltip->GetTip() , m_wxPeer->GetFont().GetEncoding() );
2357 [m_osxView setToolTip: cf.AsNSString()];
2358 // tt = [m_osxView addToolTipRect:[m_osxView bounds] owner:m_osxView userData:nil];
2364 [m_osxView removeToolTip:tt];
2371 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
2373 WXWidget c = control ? control : (WXWidget) m_osxView;
2374 wxWidgetImpl::Associate( c, this ) ;
2375 if ([c respondsToSelector:@selector(setAction:)])
2378 [c setAction: @selector(controlAction:)];
2379 if ([c respondsToSelector:@selector(setDoubleAction:)])
2381 [c setDoubleAction: @selector(controlDoubleAction:)];
2387 bool wxWidgetCocoaImpl::DoHandleCharEvent(NSEvent *event, NSString *text)
2389 wxKeyEvent wxevent(wxEVT_CHAR);
2390 SetupKeyEvent( wxevent, event, text );
2392 return GetWXPeer()->OSXHandleKeyEvent(wxevent);
2395 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
2397 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
2398 SetupKeyEvent( wxevent, event );
2400 // Generate wxEVT_CHAR_HOOK before sending any other events but only when
2401 // the key is pressed, not when it's released (the type of wxevent is
2402 // changed by SetupKeyEvent() so it can be wxEVT_KEY_UP too by now).
2403 if ( wxevent.GetEventType() == wxEVT_KEY_DOWN )
2405 wxKeyEvent eventHook(wxEVT_CHAR_HOOK, wxevent);
2406 if ( GetWXPeer()->OSXHandleKeyEvent(eventHook)
2407 && !eventHook.IsNextEventAllowed() )
2411 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
2413 // this will fire higher level events, like insertText, to help
2414 // us handle EVT_CHAR, etc.
2418 if ( IsUserPane() && [event type] == NSKeyDown)
2420 long keycode = wxOSXTranslateCocoaKey( event, wxEVT_CHAR );
2422 if ( (keycode > 0 && keycode < WXK_SPACE) || keycode == WXK_DELETE || keycode >= WXK_START )
2424 // eventually we could setup a doCommandBySelector catcher and retransform this into the wx key chars
2425 wxKeyEvent wxevent2(wxevent) ;
2426 wxevent2.SetEventType(wxEVT_CHAR);
2427 wxevent2.m_keyCode = keycode;
2428 result = GetWXPeer()->OSXHandleKeyEvent(wxevent2);
2432 if ( !wxevent.CmdDown() )
2434 if ( [m_osxView isKindOfClass:[NSScrollView class] ] )
2435 [[(NSScrollView*)m_osxView documentView] interpretKeyEvents:[NSArray arrayWithObject:event]];
2437 [m_osxView interpretKeyEvents:[NSArray arrayWithObject:event]];
2447 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
2449 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
2450 SetupMouseEvent(wxevent , event) ;
2452 return GetWXPeer()->HandleWindowEvent(wxevent);
2455 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus, wxWidgetImpl* otherWindow)
2457 wxWindow* thisWindow = GetWXPeer();
2458 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
2460 thisWindow->MacInvalidateBorders();
2463 if ( receivedFocus )
2465 wxLogTrace(wxT("Focus"), wxT("focus set(%p)"), static_cast<void*>(thisWindow));
2466 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
2467 thisWindow->HandleWindowEvent(eventFocus);
2470 if ( thisWindow->GetCaret() )
2471 thisWindow->GetCaret()->OnSetFocus();
2474 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
2475 event.SetEventObject(thisWindow);
2477 event.SetWindow(otherWindow->GetWXPeer());
2478 thisWindow->HandleWindowEvent(event) ;
2480 else // !receivedFocuss
2483 if ( thisWindow->GetCaret() )
2484 thisWindow->GetCaret()->OnKillFocus();
2487 wxLogTrace(wxT("Focus"), wxT("focus lost(%p)"), static_cast<void*>(thisWindow));
2489 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
2490 event.SetEventObject(thisWindow);
2492 event.SetWindow(otherWindow->GetWXPeer());
2493 thisWindow->HandleWindowEvent(event) ;
2497 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
2501 NSPoint location = [NSEvent mouseLocation];
2502 location = [[m_osxView window] convertScreenToBase:location];
2503 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
2505 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
2507 [(NSCursor*)cursor.GetHCURSOR() set];
2510 [[m_osxView window] invalidateCursorRectsForView:m_osxView];
2513 void wxWidgetCocoaImpl::CaptureMouse()
2515 [[m_osxView window] disableCursorRects];
2518 void wxWidgetCocoaImpl::ReleaseMouse()
2520 [[m_osxView window] enableCursorRects];
2523 void wxWidgetCocoaImpl::SetFlipped(bool flipped)
2525 m_isFlipped = flipped;
2532 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent),
2533 wxWindowID WXUNUSED(id), const wxPoint& pos, const wxSize& size,
2534 long WXUNUSED(style), long WXUNUSED(extraStyle))
2536 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
2537 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
2539 // temporary hook for dnd
2540 [v registerForDraggedTypes:[NSArray arrayWithObjects:
2541 NSStringPboardType, NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSPDFPboardType, nil]];
2543 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v, false, true );
2547 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
2549 NSWindow* tlw = now->GetWXWindow();
2551 wxWidgetCocoaImpl* c = NULL;
2552 if ( now->IsNativeWindowWrapper() )
2554 NSView* cv = [tlw contentView];
2555 c = new wxWidgetCocoaImpl( now, cv, true );
2556 // increase ref count, because the impl destructor will decrement it again
2558 if ( !now->IsShown() )
2564 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
2565 c = new wxWidgetCocoaImpl( now, v, true );
2566 c->InstallEventHandler();
2567 [tlw setContentView:v];