1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/cocoa/window.mm
3 // Purpose: widgets (non tlw) for cocoa
4 // Author: Stefan Csomor
7 // RCS-ID: $Id: window.mm 48805 2007-09-19 14:52:25Z SC $
8 // Copyright: (c) Stefan Csomor
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 #include "wx/wxprec.h"
15 #include "wx/nonownedwnd.h"
20 #include "wx/osx/private.h"
27 NSRect wxOSXGetFrameForControl( wxWindowMac* window , const wxPoint& pos , const wxSize &size , bool adjustForOrigin )
31 window->MacGetBoundsForControl( pos , size , x , y, w, h , adjustForOrigin ) ;
32 wxRect bounds(x,y,w,h);
33 NSView* sv = (window->GetParent()->GetHandle() );
35 return wxToNSRect( sv, bounds );
38 @interface wxNSView : NSView
40 WXCOCOAIMPL_COMMON_MEMBERS
43 - (void)drawRect: (NSRect) rect;
45 WXCOCOAIMPL_COMMON_INTERFACE
47 - (BOOL) canBecomeKeyView;
51 @interface NSView(PossibleMethods)
52 - (void)setImplementation:(wxWidgetCocoaImpl *)theImplementation;
53 - (void)setTitle:(NSString *)aString;
54 - (void)setStringValue:(NSString *)aString;
55 - (void)setIntValue:(int)anInt;
56 - (void)setFloatValue:(float)aFloat;
57 - (void)setDoubleValue:(double)aDouble;
61 - (void)setMinValue:(double)aDouble;
62 - (void)setMaxValue:(double)aDouble;
67 - (void)setEnabled:(BOOL)flag;
69 - (void)setImage:(NSImage *)image;
70 - (void)setControlSize:(NSControlSize)size;
75 long wxOSXTranslateCocoaKey( int unichar )
77 long retval = unichar;
80 case NSUpArrowFunctionKey :
83 case NSDownArrowFunctionKey :
86 case NSLeftArrowFunctionKey :
89 case NSRightArrowFunctionKey :
92 case NSInsertFunctionKey :
95 case NSDeleteFunctionKey :
98 case NSHomeFunctionKey :
101 // case NSBeginFunctionKey :
102 // retval = WXK_BEGIN;
104 case NSEndFunctionKey :
107 case NSPageUpFunctionKey :
110 case NSPageDownFunctionKey :
111 retval = WXK_PAGEDOWN;
113 case NSHelpFunctionKey :
118 if ( unichar >= NSF1FunctionKey && unichar >= NSF24FunctionKey )
119 retval = WXK_F1 + (unichar - NSF1FunctionKey );
125 void SetupKeyEvent( wxKeyEvent &wxevent , NSEvent * nsEvent )
127 UInt32 modifiers = [nsEvent modifierFlags] ;
128 int eventType = [nsEvent type];
130 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
131 wxevent.m_controlDown = modifiers & NSControlKeyMask;
132 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
133 wxevent.m_metaDown = modifiers & NSCommandKeyMask;
135 wxevent.m_rawCode = [nsEvent keyCode];
136 wxevent.m_rawFlags = modifiers;
138 wxevent.SetTimestamp( [nsEvent timestamp] * 1000.0 ) ;
142 wxevent.SetEventType( wxEVT_KEY_DOWN ) ;
145 wxevent.SetEventType( wxEVT_KEY_UP ) ;
147 case NSFlagsChanged :
148 // setup common code here
155 if ( eventType != NSFlagsChanged )
157 NSString* nschars = [nsEvent characters];
160 wxCFStringRef cfchars((CFStringRef)[nschars retain]);
161 chars = cfchars.AsString();
165 int unichar = chars.Length() > 0 ? chars[0] : 0;
166 long keyval = wxOSXTranslateCocoaKey(unichar) ;
167 if ( keyval == unichar && ( wxevent.GetEventType() == wxEVT_KEY_UP || wxevent.GetEventType() == wxEVT_KEY_DOWN ) )
168 keyval = wxToupper( keyval ) ;
171 wxevent.m_uniChar = unichar;
173 wxevent.m_keyCode = keyval;
176 UInt32 g_lastButton = 0 ;
177 bool g_lastButtonWasFakeRight = false ;
179 void SetupMouseEvent( wxMouseEvent &wxevent , NSEvent * nsEvent )
181 UInt32 modifiers = [nsEvent modifierFlags] ;
182 wxPoint screenMouseLocation = wxFromNSPoint( NULL, [nsEvent locationInWindow]);
184 // these parameters are not given for all events
185 UInt32 button = [nsEvent buttonNumber];
186 UInt32 clickCount = [nsEvent clickCount];
188 wxevent.m_x = screenMouseLocation.x;
189 wxevent.m_y = screenMouseLocation.y;
190 wxevent.m_shiftDown = modifiers & NSShiftKeyMask;
191 wxevent.m_controlDown = modifiers & NSControlKeyMask;
192 wxevent.m_altDown = modifiers & NSAlternateKeyMask;
193 wxevent.m_metaDown = modifiers & NSCommandKeyMask;
194 wxevent.m_clickCount = clickCount;
195 wxevent.SetTimestamp( [nsEvent timestamp] * 1000.0 ) ;
197 UInt32 mouseChord = 0;
198 int eventType = [nsEvent type];
202 case NSLeftMouseDown :
203 case NSLeftMouseDragged :
206 case NSRightMouseDown :
207 case NSRightMouseDragged :
210 case NSOtherMouseDown :
211 case NSOtherMouseDragged :
216 // a control click is interpreted as a right click
217 bool thisButtonIsFakeRight = false ;
218 if ( button == 0 && (modifiers & NSControlKeyMask) )
221 thisButtonIsFakeRight = true ;
224 // otherwise we report double clicks by connecting a left click with a ctrl-left click
225 if ( clickCount > 1 && button != g_lastButton )
228 // we must make sure that our synthetic 'right' button corresponds in
229 // mouse down, moved and mouse up, and does not deliver a right down and left up
232 case NSLeftMouseDown :
233 case NSRightMouseDown :
234 case NSOtherMouseDown :
235 g_lastButton = button ;
236 g_lastButtonWasFakeRight = thisButtonIsFakeRight ;
243 g_lastButtonWasFakeRight = false ;
245 else if ( g_lastButton == 1 && g_lastButtonWasFakeRight )
246 button = g_lastButton ;
248 // Adjust the chord mask to remove the primary button and add the
249 // secondary button. It is possible that the secondary button is
250 // already pressed, e.g. on a mouse connected to a laptop, but this
251 // possibility is ignored here:
252 if( thisButtonIsFakeRight && ( mouseChord & 1U ) )
253 mouseChord = ((mouseChord & ~1U) | 2U);
256 wxevent.m_leftDown = true ;
258 wxevent.m_rightDown = true ;
260 wxevent.m_middleDown = true ;
262 // translate into wx types
265 case NSLeftMouseDown :
266 case NSRightMouseDown :
267 case NSOtherMouseDown :
271 wxevent.SetEventType( clickCount > 1 ? wxEVT_LEFT_DCLICK : wxEVT_LEFT_DOWN ) ;
275 wxevent.SetEventType( clickCount > 1 ? wxEVT_RIGHT_DCLICK : wxEVT_RIGHT_DOWN ) ;
279 wxevent.SetEventType( clickCount > 1 ? wxEVT_MIDDLE_DCLICK : wxEVT_MIDDLE_DOWN ) ;
288 case NSRightMouseUp :
289 case NSOtherMouseUp :
293 wxevent.SetEventType( wxEVT_LEFT_UP ) ;
297 wxevent.SetEventType( wxEVT_RIGHT_UP ) ;
301 wxevent.SetEventType( wxEVT_MIDDLE_UP ) ;
311 wxevent.SetEventType( wxEVT_MOUSEWHEEL ) ;
313 EventMouseWheelAxis axis = cEvent.GetParameter<EventMouseWheelAxis>(kEventParamMouseWheelAxis, typeMouseWheelAxis) ;
314 SInt32 delta = cEvent.GetParameter<SInt32>(kEventParamMouseWheelDelta, typeSInt32) ;
316 wxevent.m_wheelRotation = 10; // delta;
317 wxevent.m_wheelDelta = 1;
318 wxevent.m_linesPerAction = 1;
319 if ( 0 /* axis == kEventMouseWheelAxisX*/ )
320 wxevent.m_wheelAxis = 1;
324 case NSMouseEntered :
326 case NSLeftMouseDragged :
327 case NSRightMouseDragged :
328 case NSOtherMouseDragged :
330 wxevent.SetEventType( wxEVT_MOTION ) ;
337 @implementation wxNSView
339 #define OSX_DEBUG_DRAWING 0
341 - (void)drawRect: (NSRect) rect
345 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
346 CGContextSaveGState( context );
347 #if OSX_DEBUG_DRAWING
348 CGContextBeginPath( context );
349 CGContextMoveToPoint(context, 0, 0);
350 NSRect bounds = [self bounds];
351 CGContextAddLineToPoint(context, 10, 0);
352 CGContextMoveToPoint(context, 0, 0);
353 CGContextAddLineToPoint(context, 0, 10);
354 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
355 CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height-10);
356 CGContextMoveToPoint(context, bounds.size.width, bounds.size.height);
357 CGContextAddLineToPoint(context, bounds.size.width-10, bounds.size.height);
358 CGContextClosePath( context );
359 CGContextStrokePath(context);
362 if ( [ self isFlipped ] == NO )
364 CGContextTranslateCTM( context, 0, [self bounds].size.height );
365 CGContextScaleCTM( context, 1, -1 );
372 [self getRectsBeingDrawn:&rects count:&count];
373 for ( int i = 0 ; i < count ; ++i )
375 updateRgn.Union(wxFromNSRect(self, rects[i]) );
378 wxWindow* wxpeer = impl->GetWXPeer();
379 wxpeer->GetUpdateRegion() = updateRgn;
380 wxpeer->MacSetCGContextRef( context );
383 event.SetTimestamp(0); // todo
384 event.SetEventObject(wxpeer);
385 wxpeer->HandleWindowEvent(event);
387 CGContextRestoreGState( context );
391 WXCOCOAIMPL_COMMON_IMPLEMENTATION
393 - (BOOL) canBecomeKeyView
400 IMPLEMENT_DYNAMIC_CLASS( wxWidgetCocoaImpl , wxWidgetImpl )
402 wxWidgetCocoaImpl::wxWidgetCocoaImpl( wxWindowMac* peer , WXWidget w, bool isRootControl ) :
403 wxWidgetImpl( peer, isRootControl ), m_osxView(w)
407 wxWidgetCocoaImpl::wxWidgetCocoaImpl()
411 void wxWidgetCocoaImpl::Init()
416 wxWidgetCocoaImpl::~wxWidgetCocoaImpl()
418 if ( [m_osxView respondsToSelector:@selector(setImplementation:) ] )
419 [m_osxView setImplementation:NULL];
420 if ( !IsRootControl() )
422 NSView *sv = [m_osxView superview];
424 [m_osxView removeFromSuperview];
429 bool wxWidgetCocoaImpl::IsVisible() const
431 return [m_osxView isHiddenOrHasHiddenAncestor] == NO;
434 void wxWidgetCocoaImpl::SetVisibility( bool visible )
436 [m_osxView setHidden:(visible ? NO:YES)];
439 void wxWidgetCocoaImpl::Raise()
443 void wxWidgetCocoaImpl::Lower()
447 void wxWidgetCocoaImpl::ScrollRect( const wxRect *rect, int dx, int dy )
452 // We should do something like this, but it wasn't working in 10.4.
453 if (GetNeedsDisplay() )
457 NSRect r = wxToNSRect( [m_osxView superview], *rect );
458 NSSize offset = NSMakeSize((float)dx, (float)dy);
459 [m_osxView scrollRect:r by:offset];
463 void wxWidgetCocoaImpl::Move(int x, int y, int width, int height)
465 wxWindowMac* parent = GetWXPeer()->GetParent();
466 // under Cocoa we might have a contentView in the wxParent to which we have to
467 // adjust the coordinates
470 wxPoint pt(parent->GetClientAreaOrigin());
474 NSRect r = wxToNSRect( [m_osxView superview], wxRect(x,y,width, height) );
475 [m_osxView setFrame:r];
478 void wxWidgetCocoaImpl::GetPosition( int &x, int &y ) const
480 wxRect r = wxFromNSRect( [m_osxView superview], [m_osxView frame] );
485 void wxWidgetCocoaImpl::GetSize( int &width, int &height ) const
487 NSRect rect = [m_osxView frame];
488 width = rect.size.width;
489 height = rect.size.height;
492 void wxWidgetCocoaImpl::GetContentArea( int&left, int &top, int &width, int &height ) const
494 if ( [m_osxView respondsToSelector:@selector(contentView) ] )
496 NSView* cv = [m_osxView contentView];
498 NSRect bounds = [m_osxView bounds];
499 NSRect rect = [cv frame];
501 int y = rect.origin.y;
502 int x = rect.origin.x;
503 if ( ![ m_osxView isFlipped ] )
504 y = bounds.size.height - (rect.origin.y + rect.size.height);
507 width = rect.size.width;
508 height = rect.size.height;
513 GetSize( width, height );
517 void wxWidgetCocoaImpl::SetNeedsDisplay( const wxRect* where )
520 [m_osxView setNeedsDisplayInRect:wxToNSRect(m_osxView, *where )];
522 [m_osxView setNeedsDisplay:YES];
525 bool wxWidgetCocoaImpl::GetNeedsDisplay() const
527 return [m_osxView needsDisplay];
530 bool wxWidgetCocoaImpl::CanFocus() const
532 return [m_osxView canBecomeKeyView] == YES;
535 bool wxWidgetCocoaImpl::HasFocus() const
537 return ( [[m_osxView window] firstResponder] == m_osxView );
540 bool wxWidgetCocoaImpl::SetFocus()
542 if ( [m_osxView canBecomeKeyView] == NO )
545 [[m_osxView window] makeFirstResponder: m_osxView] ;
550 void wxWidgetCocoaImpl::RemoveFromParent()
552 [m_osxView removeFromSuperview];
555 void wxWidgetCocoaImpl::Embed( wxWidgetImpl *parent )
557 NSView* container = parent->GetWXWidget() ;
558 wxASSERT_MSG( container != NULL , wxT("No valid mac container control") ) ;
559 [container addSubview:m_osxView];
562 void wxWidgetCocoaImpl::SetBackgroundColour( const wxColour &WXUNUSED(col) )
564 // m_osxView.backgroundColor = [[UIColor alloc] initWithCGColor:col.GetCGColor()];
567 void wxWidgetCocoaImpl::SetLabel( const wxString& title, wxFontEncoding encoding )
569 if ( [m_osxView respondsToSelector:@selector(setTitle:) ] )
571 wxCFStringRef cf( title , m_wxPeer->GetFont().GetEncoding() );
572 [m_osxView setTitle:cf.AsNSString()];
577 void wxWidgetImpl::Convert( wxPoint *pt , wxWidgetImpl *from , wxWidgetImpl *to )
579 NSPoint p = wxToNSPoint( from->GetWXWidget(), *pt );
580 p = [from->GetWXWidget() convertPoint:p toView:to->GetWXWidget() ];
581 *pt = wxFromNSPoint( to->GetWXWidget(), p );
584 wxInt32 wxWidgetCocoaImpl::GetValue() const
586 return [(NSControl*)m_osxView intValue];
589 void wxWidgetCocoaImpl::SetValue( wxInt32 v )
591 if ( [m_osxView respondsToSelector:@selector(setIntValue:)] )
593 [m_osxView setIntValue:v];
595 else if ( [m_osxView respondsToSelector:@selector(setFloatValue:)] )
597 [m_osxView setFloatValue:(double)v];
599 else if ( [m_osxView respondsToSelector:@selector(setDoubleValue:)] )
601 [m_osxView setDoubleValue:(double)v];
605 void wxWidgetCocoaImpl::SetMinimum( wxInt32 v )
607 if ( [m_osxView respondsToSelector:@selector(setMinValue:)] )
609 [m_osxView setMinValue:(double)v];
613 void wxWidgetCocoaImpl::SetMaximum( wxInt32 v )
615 if ( [m_osxView respondsToSelector:@selector(setMaxValue:)] )
617 [m_osxView setMaxValue:(double)v];
621 wxInt32 wxWidgetCocoaImpl::GetMinimum() const
623 if ( [m_osxView respondsToSelector:@selector(getMinValue:)] )
625 return [m_osxView minValue];
630 wxInt32 wxWidgetCocoaImpl::GetMaximum() const
632 if ( [m_osxView respondsToSelector:@selector(getMaxValue:)] )
634 return [m_osxView maxValue];
639 void wxWidgetCocoaImpl::SetBitmap( const wxBitmap& bitmap )
641 if ( [m_osxView respondsToSelector:@selector(setImage:)] )
643 [m_osxView setImage:bitmap.GetNSImage()];
647 void wxWidgetCocoaImpl::SetupTabs( const wxNotebook& notebook)
649 // implementation in subclass
652 void wxWidgetCocoaImpl::GetBestRect( wxRect *r ) const
654 r->x = r->y = r->width = r->height = 0;
655 // if ( [m_osxView isKindOfClass:[NSControl class]] )
656 if ( [m_osxView respondsToSelector:@selector(sizeToFit)] )
658 NSRect former = [m_osxView frame];
659 [m_osxView sizeToFit];
660 NSRect best = [m_osxView frame];
661 [m_osxView setFrame:former];
662 r->width = best.size.width;
663 r->height = best.size.height;
667 bool wxWidgetCocoaImpl::IsEnabled() const
669 if ( [m_osxView respondsToSelector:@selector(isEnabled) ] )
670 return [m_osxView isEnabled];
674 void wxWidgetCocoaImpl::Enable( bool enable )
676 if ( [m_osxView respondsToSelector:@selector(setEnabled:) ] )
677 [m_osxView setEnabled:enable];
680 void wxWidgetCocoaImpl::PulseGauge()
684 void wxWidgetCocoaImpl::SetScrollThumb( wxInt32 val, wxInt32 view )
688 void wxWidgetCocoaImpl::SetControlSize( wxWindowVariant variant )
690 NSControlSize size = NSRegularControlSize;
694 case wxWINDOW_VARIANT_NORMAL :
695 size = NSRegularControlSize;
698 case wxWINDOW_VARIANT_SMALL :
699 size = NSSmallControlSize;
702 case wxWINDOW_VARIANT_MINI :
703 size = NSMiniControlSize;
706 case wxWINDOW_VARIANT_LARGE :
707 size = NSRegularControlSize;
711 wxFAIL_MSG(_T("unexpected window variant"));
714 if ( [m_osxView respondsToSelector:@selector(setControlSize:)] )
715 [m_osxView setControlSize:size];
718 void wxWidgetCocoaImpl::SetFont(wxFont const&, wxColour const&, long, bool)
723 void wxWidgetCocoaImpl::InstallEventHandler( WXWidget control )
727 bool wxWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
729 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
730 SetupKeyEvent( wxevent, event );
732 return GetWXPeer()->OSXHandleKeyEvent(wxevent);
735 bool wxWidgetCocoaImpl::DoHandleMouseEvent(NSEvent *event)
737 NSPoint clickLocation;
738 clickLocation = [m_osxView convertPoint:[event locationInWindow] fromView:nil];
739 wxPoint pt = wxFromNSPoint( m_osxView, clickLocation );
740 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
741 SetupMouseEvent( wxevent , event ) ;
745 return GetWXPeer()->HandleWindowEvent(wxevent);
748 void wxWidgetCocoaImpl::DoNotifyFocusEvent(bool receivedFocus)
750 wxWindow* thisWindow = GetWXPeer();
751 if ( thisWindow->MacGetTopLevelWindow() && NeedsFocusRect() )
753 thisWindow->MacInvalidateBorders();
758 wxLogTrace(_T("Focus"), _T("focus set(%p)"), static_cast<void*>(thisWindow));
759 wxChildFocusEvent eventFocus((wxWindow*)thisWindow);
760 thisWindow->HandleWindowEvent(eventFocus);
763 if ( thisWindow->GetCaret() )
764 thisWindow->GetCaret()->OnSetFocus();
767 wxFocusEvent event(wxEVT_SET_FOCUS, thisWindow->GetId());
768 event.SetEventObject(thisWindow);
769 // TODO how to find out the targetFocusWindow ?
770 // event.SetWindow(targetFocusWindow);
771 thisWindow->HandleWindowEvent(event) ;
773 else // !receivedFocuss
776 if ( thisWindow->GetCaret() )
777 thisWindow->GetCaret()->OnKillFocus();
780 wxLogTrace(_T("Focus"), _T("focus lost(%p)"), static_cast<void*>(thisWindow));
782 wxFocusEvent event( wxEVT_KILL_FOCUS, thisWindow->GetId());
783 event.SetEventObject(thisWindow);
784 // TODO how to find out the targetFocusWindow ?
785 // event.SetWindow(targetFocusWindow);
786 thisWindow->HandleWindowEvent(event) ;
790 void wxWidgetCocoaImpl::SetCursor(const wxCursor& cursor)
792 NSPoint location = [NSEvent mouseLocation];
793 location = [[m_osxView window] convertScreenToBase:location];
794 NSPoint locationInView = [m_osxView convertPoint:location fromView:nil];
796 if( NSMouseInRect(locationInView, [m_osxView bounds], YES) )
798 [(NSCursor*)cursor.GetHCURSOR() set];
800 [[m_osxView window] invalidateCursorRectsForView:m_osxView];
803 void wxWidgetCocoaImpl::CaptureMouse()
805 [[m_osxView window] disableCursorRects];
808 void wxWidgetCocoaImpl::ReleaseMouse()
810 [[m_osxView window] enableCursorRects];
817 wxWidgetImpl* wxWidgetImpl::CreateUserPane( wxWindowMac* wxpeer, wxWindowMac* parent, wxWindowID id, const wxPoint& pos, const wxSize& size,
818 long style, long extraStyle)
820 NSView* sv = (wxpeer->GetParent()->GetHandle() );
822 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
823 wxNSView* v = [[wxNSView alloc] initWithFrame:r];
825 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( wxpeer, v );
826 [v setImplementation:c];
830 wxWidgetImpl* wxWidgetImpl::CreateContentView( wxNonOwnedWindow* now )
832 NSWindow* tlw = now->GetWXWindow();
833 wxNSView* v = [[wxNSView alloc] initWithFrame:[[tlw contentView] frame]];
834 wxWidgetCocoaImpl* c = new wxWidgetCocoaImpl( now, v, true );
835 [v setImplementation:c];
836 [tlw setContentView:v];