1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/cocoa/window.mm
3 // Purpose: wxWindowCocoa
4 // Author: David Elliott
8 // Copyright: (c) 2002 David Elliott
9 // Licence: wxWidgets licence
10 /////////////////////////////////////////////////////////////////////////////
12 #include "wx/wxprec.h"
16 #include "wx/window.h"
21 #include "wx/tooltip.h"
23 #include "wx/cocoa/autorelease.h"
24 #include "wx/cocoa/string.h"
25 #include "wx/cocoa/trackingrectmanager.h"
27 #import <Foundation/NSRunLoop.h>
28 #include "wx/cocoa/objc/NSView.h"
29 #import <AppKit/NSEvent.h>
30 #import <AppKit/NSScrollView.h>
31 #import <AppKit/NSColor.h>
32 #import <AppKit/NSClipView.h>
33 #import <Foundation/NSException.h>
34 #import <AppKit/NSApplication.h>
35 #import <AppKit/NSWindow.h>
37 // Turn this on to paint green over the dummy views for debugging
38 #undef WXCOCOA_FILL_DUMMY_VIEW
40 #ifdef WXCOCOA_FILL_DUMMY_VIEW
41 #import <AppKit/NSBezierPath.h>
42 #endif //def WXCOCOA_FILL_DUMMY_VIEW
44 // A category for methods that are only present in Panther's SDK
45 @interface NSView(wxNSViewPrePantherCompatibility)
46 - (void)getRectsBeingDrawn:(const NSRect **)rects count:(int *)count;
49 NSPoint CocoaTransformNSViewBoundsToWx(NSView *nsview, NSPoint pointBounds)
51 wxCHECK_MSG(nsview, pointBounds, wxT("Need to have a Cocoa view to do translation"));
52 if([nsview isFlipped])
54 NSRect ourBounds = [nsview bounds];
57 , ourBounds.size.height - pointBounds.y
61 NSRect CocoaTransformNSViewBoundsToWx(NSView *nsview, NSRect rectBounds)
63 wxCHECK_MSG(nsview, rectBounds, wxT("Need to have a Cocoa view to do translation"));
64 if([nsview isFlipped])
66 NSRect ourBounds = [nsview bounds];
69 , ourBounds.size.height - (rectBounds.origin.y + rectBounds.size.height)
70 , rectBounds.size.width
71 , rectBounds.size.height
75 NSPoint CocoaTransformNSViewWxToBounds(NSView *nsview, NSPoint pointWx)
77 wxCHECK_MSG(nsview, pointWx, wxT("Need to have a Cocoa view to do translation"));
78 if([nsview isFlipped])
80 NSRect ourBounds = [nsview bounds];
83 , ourBounds.size.height - pointWx.y
87 NSRect CocoaTransformNSViewWxToBounds(NSView *nsview, NSRect rectWx)
89 wxCHECK_MSG(nsview, rectWx, wxT("Need to have a Cocoa view to do translation"));
90 if([nsview isFlipped])
92 NSRect ourBounds = [nsview bounds];
95 , ourBounds.size.height - (rectWx.origin.y + rectWx.size.height)
101 // ========================================================================
102 // wxWindowCocoaHider
103 // ========================================================================
104 class wxWindowCocoaHider: protected wxCocoaNSView
106 DECLARE_NO_COPY_CLASS(wxWindowCocoaHider)
108 wxWindowCocoaHider(wxWindow *owner);
109 virtual ~wxWindowCocoaHider();
110 inline WX_NSView GetNSView() { return m_dummyNSView; }
112 wxWindowCocoa *m_owner;
113 WX_NSView m_dummyNSView;
114 virtual void Cocoa_FrameChanged(void);
115 virtual void Cocoa_synthesizeMouseMoved(void) {}
116 #ifdef WXCOCOA_FILL_DUMMY_VIEW
117 virtual bool Cocoa_drawRect(const NSRect& rect);
118 #endif //def WXCOCOA_FILL_DUMMY_VIEW
120 wxWindowCocoaHider();
123 // ========================================================================
124 // wxWindowCocoaScrollView
125 // ========================================================================
126 class wxWindowCocoaScrollView: protected wxCocoaNSView
128 DECLARE_NO_COPY_CLASS(wxWindowCocoaScrollView)
130 wxWindowCocoaScrollView(wxWindow *owner);
131 virtual ~wxWindowCocoaScrollView();
132 inline WX_NSScrollView GetNSScrollView() { return m_cocoaNSScrollView; }
133 void ClientSizeToSize(int &width, int &height);
134 void DoGetClientSize(int *x, int *y) const;
136 void Unencapsulate();
138 wxWindowCocoa *m_owner;
139 WX_NSScrollView m_cocoaNSScrollView;
140 virtual void Cocoa_FrameChanged(void);
141 virtual void Cocoa_synthesizeMouseMoved(void) {}
143 wxWindowCocoaScrollView();
146 // ========================================================================
148 // ========================================================================
149 @interface wxDummyNSView : NSView
150 - (NSView *)hitTest:(NSPoint)aPoint;
152 WX_DECLARE_GET_OBJC_CLASS(wxDummyNSView,NSView)
154 @implementation wxDummyNSView : NSView
155 - (NSView *)hitTest:(NSPoint)aPoint
161 WX_IMPLEMENT_GET_OBJC_CLASS(wxDummyNSView,NSView)
163 // ========================================================================
164 // wxWindowCocoaHider
165 // ========================================================================
166 wxWindowCocoaHider::wxWindowCocoaHider(wxWindow *owner)
170 wxASSERT(owner->GetNSViewForHiding());
171 m_dummyNSView = [[WX_GET_OBJC_CLASS(wxDummyNSView) alloc]
172 initWithFrame:[owner->GetNSViewForHiding() frame]];
173 [m_dummyNSView setAutoresizingMask: [owner->GetNSViewForHiding() autoresizingMask]];
174 AssociateNSView(m_dummyNSView);
177 wxWindowCocoaHider::~wxWindowCocoaHider()
179 DisassociateNSView(m_dummyNSView);
180 [m_dummyNSView release];
183 void wxWindowCocoaHider::Cocoa_FrameChanged(void)
185 // Keep the real window in synch with the dummy
186 wxASSERT(m_dummyNSView);
187 [m_owner->GetNSViewForHiding() setFrame:[m_dummyNSView frame]];
191 #ifdef WXCOCOA_FILL_DUMMY_VIEW
192 bool wxWindowCocoaHider::Cocoa_drawRect(const NSRect& rect)
194 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:rect];
195 [[NSColor greenColor] set];
200 #endif //def WXCOCOA_FILL_DUMMY_VIEW
202 // ========================================================================
203 // wxFlippedNSClipView
204 // ========================================================================
205 @interface wxFlippedNSClipView : NSClipView
208 WX_DECLARE_GET_OBJC_CLASS(wxFlippedNSClipView,NSClipView)
210 @implementation wxFlippedNSClipView : NSClipView
217 WX_IMPLEMENT_GET_OBJC_CLASS(wxFlippedNSClipView,NSClipView)
219 // ========================================================================
220 // wxWindowCocoaScrollView
221 // ========================================================================
222 wxWindowCocoaScrollView::wxWindowCocoaScrollView(wxWindow *owner)
225 wxAutoNSAutoreleasePool pool;
227 wxASSERT(owner->GetNSView());
228 m_cocoaNSScrollView = [[NSScrollView alloc]
229 initWithFrame:[owner->GetNSView() frame]];
230 AssociateNSView(m_cocoaNSScrollView);
232 /* Replace the default NSClipView with a flipped one. This ensures
233 scrolling is "pinned" to the top-left instead of bottom-right. */
234 NSClipView *flippedClip = [[WX_GET_OBJC_CLASS(wxFlippedNSClipView) alloc]
235 initWithFrame: [[m_cocoaNSScrollView contentView] frame]];
236 [m_cocoaNSScrollView setContentView:flippedClip];
237 [flippedClip release];
239 [m_cocoaNSScrollView setBackgroundColor: [NSColor windowBackgroundColor]];
240 [m_cocoaNSScrollView setHasHorizontalScroller: YES];
241 [m_cocoaNSScrollView setHasVerticalScroller: YES];
245 void wxWindowCocoaScrollView::Encapsulate()
247 // Set the scroll view autoresizingMask to match the current NSView
248 [m_cocoaNSScrollView setAutoresizingMask: [m_owner->GetNSView() autoresizingMask]];
249 [m_owner->GetNSView() setAutoresizingMask: NSViewNotSizable];
250 // NOTE: replaceSubView will cause m_cocaNSView to be released
251 // except when it hasn't been added into an NSView hierarchy in which
252 // case it doesn't need to be and this should work out to a no-op
253 m_owner->CocoaReplaceView(m_owner->GetNSView(), m_cocoaNSScrollView);
254 // The NSView is still retained by owner
255 [m_cocoaNSScrollView setDocumentView: m_owner->GetNSView()];
256 // Now it's also retained by the NSScrollView
259 void wxWindowCocoaScrollView::Unencapsulate()
261 [m_cocoaNSScrollView setDocumentView: nil];
262 m_owner->CocoaReplaceView(m_cocoaNSScrollView, m_owner->GetNSView());
263 if(![[m_owner->GetNSView() superview] isFlipped])
264 [m_owner->GetNSView() setAutoresizingMask: NSViewMinYMargin];
267 wxWindowCocoaScrollView::~wxWindowCocoaScrollView()
269 DisassociateNSView(m_cocoaNSScrollView);
270 [m_cocoaNSScrollView release];
273 void wxWindowCocoaScrollView::ClientSizeToSize(int &width, int &height)
275 NSSize frameSize = [NSScrollView
276 frameSizeForContentSize: NSMakeSize(width,height)
277 hasHorizontalScroller: [m_cocoaNSScrollView hasHorizontalScroller]
278 hasVerticalScroller: [m_cocoaNSScrollView hasVerticalScroller]
279 borderType: [m_cocoaNSScrollView borderType]];
280 width = (int)frameSize.width;
281 height = (int)frameSize.height;
284 void wxWindowCocoaScrollView::DoGetClientSize(int *x, int *y) const
286 NSSize nssize = [m_cocoaNSScrollView contentSize];
288 *x = (int)nssize.width;
290 *y = (int)nssize.height;
293 void wxWindowCocoaScrollView::Cocoa_FrameChanged(void)
295 wxLogTrace(wxTRACE_COCOA,wxT("Cocoa_FrameChanged"));
296 wxSizeEvent event(m_owner->GetSize(), m_owner->GetId());
297 event.SetEventObject(m_owner);
298 m_owner->GetEventHandler()->ProcessEvent(event);
301 // ========================================================================
303 // ========================================================================
304 // normally the base classes aren't included, but wxWindow is special
305 #ifdef __WXUNIVERSAL__
306 IMPLEMENT_ABSTRACT_CLASS(wxWindowCocoa, wxWindowBase)
308 IMPLEMENT_DYNAMIC_CLASS(wxWindow, wxWindowBase)
311 BEGIN_EVENT_TABLE(wxWindowCocoa, wxWindowBase)
314 wxWindow *wxWindowCocoa::sm_capturedWindow = NULL;
317 void wxWindowCocoa::Init()
319 m_cocoaNSView = NULL;
321 m_wxCocoaScrollView = NULL;
322 m_isBeingDeleted = false;
324 m_visibleTrackingRectManager = NULL;
328 bool wxWindow::Create(wxWindow *parent, wxWindowID winid,
332 const wxString& name)
334 if(!CreateBase(parent,winid,pos,size,style,wxDefaultValidator,name))
337 // TODO: create the window
338 m_cocoaNSView = NULL;
339 SetNSView([[WX_GET_OBJC_CLASS(WXNSView) alloc] initWithFrame: MakeDefaultNSRect(size)]);
340 [m_cocoaNSView release];
344 m_parent->AddChild(this);
345 m_parent->CocoaAddChild(this);
346 SetInitialFrameRect(pos,size);
353 wxWindow::~wxWindow()
355 wxAutoNSAutoreleasePool pool;
358 // Make sure our parent (in the wxWidgets sense) is our superview
359 // before we go removing from it.
360 if(m_parent && m_parent->GetNSView()==[GetNSViewForSuperview() superview])
361 CocoaRemoveFromParent();
363 delete m_wxCocoaScrollView;
369 void wxWindowCocoa::CocoaAddChild(wxWindowCocoa *child)
371 NSView *childView = child->GetNSViewForSuperview();
374 [m_cocoaNSView addSubview: childView];
375 child->m_isShown = !m_cocoaHider;
378 void wxWindowCocoa::CocoaRemoveFromParent(void)
380 [GetNSViewForSuperview() removeFromSuperview];
383 void wxWindowCocoa::SetNSView(WX_NSView cocoaNSView)
385 // Clear the visible area tracking rect if we have one.
386 delete m_visibleTrackingRectManager;
387 m_visibleTrackingRectManager = NULL;
389 bool need_debug = cocoaNSView || m_cocoaNSView;
390 if(need_debug) wxLogTrace(wxTRACE_COCOA_RetainRelease,wxT("wxWindowCocoa=%p::SetNSView [m_cocoaNSView=%p retainCount]=%d"),this,m_cocoaNSView,[m_cocoaNSView retainCount]);
391 DisassociateNSView(m_cocoaNSView);
392 [cocoaNSView retain];
393 [m_cocoaNSView release];
394 m_cocoaNSView = cocoaNSView;
395 AssociateNSView(m_cocoaNSView);
396 if(need_debug) wxLogTrace(wxTRACE_COCOA_RetainRelease,wxT("wxWindowCocoa=%p::SetNSView [cocoaNSView=%p retainCount]=%d"),this,cocoaNSView,[cocoaNSView retainCount]);
399 WX_NSView wxWindowCocoa::GetNSViewForSuperview() const
402 ? m_cocoaHider->GetNSView()
403 : m_wxCocoaScrollView
404 ? m_wxCocoaScrollView->GetNSScrollView()
408 WX_NSView wxWindowCocoa::GetNSViewForHiding() const
410 return m_wxCocoaScrollView
411 ? m_wxCocoaScrollView->GetNSScrollView()
415 NSPoint wxWindowCocoa::CocoaTransformBoundsToWx(NSPoint pointBounds)
417 // TODO: Handle scrolling offset
418 return CocoaTransformNSViewBoundsToWx(GetNSView(), pointBounds);
421 NSRect wxWindowCocoa::CocoaTransformBoundsToWx(NSRect rectBounds)
423 // TODO: Handle scrolling offset
424 return CocoaTransformNSViewBoundsToWx(GetNSView(), rectBounds);
427 NSPoint wxWindowCocoa::CocoaTransformWxToBounds(NSPoint pointWx)
429 // TODO: Handle scrolling offset
430 return CocoaTransformNSViewWxToBounds(GetNSView(), pointWx);
433 NSRect wxWindowCocoa::CocoaTransformWxToBounds(NSRect rectWx)
435 // TODO: Handle scrolling offset
436 return CocoaTransformNSViewWxToBounds(GetNSView(), rectWx);
439 WX_NSAffineTransform wxWindowCocoa::CocoaGetWxToBoundsTransform()
441 // TODO: Handle scrolling offset
442 NSAffineTransform *transform = wxDC::CocoaGetWxToBoundsTransform([GetNSView() isFlipped], [GetNSView() bounds].size.height);
446 bool wxWindowCocoa::Cocoa_drawRect(const NSRect &rect)
448 wxLogTrace(wxTRACE_COCOA,wxT("Cocoa_drawRect"));
449 // Recursion can happen if the event loop runs from within the paint
450 // handler. For instance, if an assertion dialog is shown.
451 // FIXME: This seems less than ideal.
454 wxLogDebug(wxT("Paint event recursion!"));
459 // Set m_updateRegion
460 const NSRect *rects = ▭ // The bounding box of the region
462 // Try replacing the larger rectangle with a list of smaller ones:
463 if ([GetNSView() respondsToSelector:@selector(getRectsBeingDrawn:count:)])
464 [GetNSView() getRectsBeingDrawn:&rects count:&countRects];
466 NSRect *transformedRects = (NSRect*)malloc(sizeof(NSRect)*countRects);
467 for(int i=0; i<countRects; i++)
469 transformedRects[i] = CocoaTransformBoundsToWx(rects[i]);
471 m_updateRegion = wxRegion(transformedRects,countRects);
472 free(transformedRects);
474 wxPaintEvent event(m_windowId);
475 event.SetEventObject(this);
476 bool ret = GetEventHandler()->ProcessEvent(event);
481 void wxWindowCocoa::InitMouseEvent(wxMouseEvent& event, WX_NSEvent cocoaEvent)
483 wxASSERT_MSG([m_cocoaNSView window]==[cocoaEvent window],wxT("Mouse event for different NSWindow"));
484 // Mouse events happen at the NSWindow level so we need to convert
485 // into our bounds coordinates then convert to wx coordinates.
486 NSPoint cocoaPoint = [m_cocoaNSView convertPoint:[(NSEvent*)cocoaEvent locationInWindow] fromView:nil];
487 NSPoint pointWx = CocoaTransformBoundsToWx(cocoaPoint);
488 // FIXME: Should we be adjusting for client area origin?
489 const wxPoint &clientorigin = GetClientAreaOrigin();
490 event.m_x = (wxCoord)pointWx.x - clientorigin.x;
491 event.m_y = (wxCoord)pointWx.y - clientorigin.y;
493 event.m_shiftDown = [cocoaEvent modifierFlags] & NSShiftKeyMask;
494 event.m_controlDown = [cocoaEvent modifierFlags] & NSControlKeyMask;
495 event.m_altDown = [cocoaEvent modifierFlags] & NSAlternateKeyMask;
496 event.m_metaDown = [cocoaEvent modifierFlags] & NSCommandKeyMask;
498 // TODO: set timestamp?
499 event.SetEventObject(this);
500 event.SetId(GetId());
503 bool wxWindowCocoa::Cocoa_mouseMoved(WX_NSEvent theEvent)
505 wxMouseEvent event(wxEVT_MOTION);
506 InitMouseEvent(event,theEvent);
507 wxLogTrace(wxTRACE_COCOA,wxT("wxWindow=%p::Cocoa_mouseMoved @%d,%d"),this,event.m_x,event.m_y);
508 return GetEventHandler()->ProcessEvent(event);
511 void wxWindowCocoa::Cocoa_synthesizeMouseMoved()
513 wxMouseEvent event(wxEVT_MOTION);
514 NSWindow *window = [GetNSView() window];
515 NSPoint locationInWindow = [window mouseLocationOutsideOfEventStream];
516 NSPoint cocoaPoint = [m_cocoaNSView convertPoint:locationInWindow fromView:nil];
518 NSPoint pointWx = CocoaTransformBoundsToWx(cocoaPoint);
519 // FIXME: Should we be adjusting for client area origin?
520 const wxPoint &clientorigin = GetClientAreaOrigin();
521 event.m_x = (wxCoord)pointWx.x - clientorigin.x;
522 event.m_y = (wxCoord)pointWx.y - clientorigin.y;
524 // TODO: Handle shift, control, alt, meta flags
525 event.SetEventObject(this);
526 event.SetId(GetId());
528 wxLogTrace(wxTRACE_COCOA,wxT("wxwin=%p Synthesized Mouse Moved @%d,%d"),this,event.m_x,event.m_y);
529 GetEventHandler()->ProcessEvent(event);
532 bool wxWindowCocoa::Cocoa_mouseEntered(WX_NSEvent theEvent)
534 if(m_visibleTrackingRectManager != NULL && m_visibleTrackingRectManager->IsOwnerOfEvent(theEvent))
536 m_visibleTrackingRectManager->BeginSynthesizingEvents();
538 // Although we synthesize the mouse moved events we don't poll for them but rather send them only when
539 // some other event comes in. That other event is (guess what) mouse moved events that will be sent
540 // to the NSWindow which will forward them on to the first responder. We are not likely to be the
541 // first responder, so the mouseMoved: events are effectively discarded.
542 [[GetNSView() window] setAcceptsMouseMovedEvents:YES];
544 wxMouseEvent event(wxEVT_ENTER_WINDOW);
545 InitMouseEvent(event,theEvent);
546 wxLogTrace(wxTRACE_COCOA,wxT("wxwin=%p Mouse Entered @%d,%d"),this,event.m_x,event.m_y);
547 return GetEventHandler()->ProcessEvent(event);
553 bool wxWindowCocoa::Cocoa_mouseExited(WX_NSEvent theEvent)
555 if(m_visibleTrackingRectManager != NULL && m_visibleTrackingRectManager->IsOwnerOfEvent(theEvent))
557 m_visibleTrackingRectManager->StopSynthesizingEvents();
559 wxMouseEvent event(wxEVT_LEAVE_WINDOW);
560 InitMouseEvent(event,theEvent);
561 wxLogTrace(wxTRACE_COCOA,wxT("wxwin=%p Mouse Exited @%d,%d"),this,event.m_x,event.m_y);
562 return GetEventHandler()->ProcessEvent(event);
568 bool wxWindowCocoa::Cocoa_mouseDown(WX_NSEvent theEvent)
570 wxMouseEvent event([theEvent clickCount]<2?wxEVT_LEFT_DOWN:wxEVT_LEFT_DCLICK);
571 InitMouseEvent(event,theEvent);
572 wxLogTrace(wxTRACE_COCOA,wxT("Mouse Down @%d,%d num clicks=%d"),event.m_x,event.m_y,[theEvent clickCount]);
573 return GetEventHandler()->ProcessEvent(event);
576 bool wxWindowCocoa::Cocoa_mouseDragged(WX_NSEvent theEvent)
578 wxMouseEvent event(wxEVT_MOTION);
579 InitMouseEvent(event,theEvent);
580 event.m_leftDown = true;
581 wxLogTrace(wxTRACE_COCOA,wxT("Mouse Drag @%d,%d"),event.m_x,event.m_y);
582 return GetEventHandler()->ProcessEvent(event);
585 bool wxWindowCocoa::Cocoa_mouseUp(WX_NSEvent theEvent)
587 wxMouseEvent event(wxEVT_LEFT_UP);
588 InitMouseEvent(event,theEvent);
589 wxLogTrace(wxTRACE_COCOA,wxT("Mouse Up @%d,%d"),event.m_x,event.m_y);
590 return GetEventHandler()->ProcessEvent(event);
593 bool wxWindowCocoa::Cocoa_rightMouseDown(WX_NSEvent theEvent)
595 wxMouseEvent event([theEvent clickCount]<2?wxEVT_RIGHT_DOWN:wxEVT_RIGHT_DCLICK);
596 InitMouseEvent(event,theEvent);
597 wxLogDebug(wxT("Mouse Down @%d,%d num clicks=%d"),event.m_x,event.m_y,[theEvent clickCount]);
598 return GetEventHandler()->ProcessEvent(event);
601 bool wxWindowCocoa::Cocoa_rightMouseDragged(WX_NSEvent theEvent)
603 wxMouseEvent event(wxEVT_MOTION);
604 InitMouseEvent(event,theEvent);
605 event.m_rightDown = true;
606 wxLogDebug(wxT("Mouse Drag @%d,%d"),event.m_x,event.m_y);
607 return GetEventHandler()->ProcessEvent(event);
610 bool wxWindowCocoa::Cocoa_rightMouseUp(WX_NSEvent theEvent)
612 wxMouseEvent event(wxEVT_RIGHT_UP);
613 InitMouseEvent(event,theEvent);
614 wxLogDebug(wxT("Mouse Up @%d,%d"),event.m_x,event.m_y);
615 return GetEventHandler()->ProcessEvent(event);
618 bool wxWindowCocoa::Cocoa_otherMouseDown(WX_NSEvent theEvent)
623 bool wxWindowCocoa::Cocoa_otherMouseDragged(WX_NSEvent theEvent)
628 bool wxWindowCocoa::Cocoa_otherMouseUp(WX_NSEvent theEvent)
633 void wxWindowCocoa::Cocoa_FrameChanged(void)
635 wxLogTrace(wxTRACE_COCOA,wxT("wxWindow=%p::Cocoa_FrameChanged"),this);
636 if(m_visibleTrackingRectManager != NULL)
637 m_visibleTrackingRectManager->RebuildTrackingRect();
638 wxSizeEvent event(GetSize(), m_windowId);
639 event.SetEventObject(this);
640 GetEventHandler()->ProcessEvent(event);
643 bool wxWindowCocoa::Cocoa_resetCursorRects()
645 wxLogTrace(wxTRACE_COCOA,wxT("wxWindow=%p::Cocoa_resetCursorRects"),this);
646 if(m_visibleTrackingRectManager != NULL)
647 m_visibleTrackingRectManager->RebuildTrackingRect();
649 if(!m_cursor.GetNSCursor())
652 [GetNSView() addCursorRect: [GetNSView() visibleRect] cursor: m_cursor.GetNSCursor()];
657 bool wxWindowCocoa::Cocoa_viewDidMoveToWindow()
659 wxLogTrace(wxTRACE_COCOA,wxT("wxWindow=%p::viewDidMoveToWindow"),this);
660 // Set up new tracking rects. I am reasonably sure the new window must be set before doing this.
661 if(m_visibleTrackingRectManager != NULL)
662 m_visibleTrackingRectManager->BuildTrackingRect();
666 bool wxWindowCocoa::Cocoa_viewWillMoveToWindow(WX_NSWindow newWindow)
668 wxLogTrace(wxTRACE_COCOA,wxT("wxWindow=%p::viewWillMoveToWindow:%p"),this, newWindow);
669 // Clear tracking rects. It is imperative this be done before the new window is set.
670 if(m_visibleTrackingRectManager != NULL)
671 m_visibleTrackingRectManager->ClearTrackingRect();
675 bool wxWindow::Close(bool force)
677 // The only reason this function exists is that it is virtual and
678 // wxTopLevelWindowCocoa will override it.
679 return wxWindowBase::Close(force);
682 void wxWindow::CocoaReplaceView(WX_NSView oldView, WX_NSView newView)
684 [[oldView superview] replaceSubview:oldView with:newView];
687 void wxWindow::DoEnable(bool enable)
689 CocoaSetEnabled(enable);
692 bool wxWindow::Show(bool show)
694 wxAutoNSAutoreleasePool pool;
695 // If the window is marked as visible, then it shouldn't have a dummy view
696 // If the window is marked hidden, then it should have a dummy view
697 // wxSpinCtrl (generic) abuses m_isShown, don't use it for any logic
698 // wxASSERT_MSG( (m_isShown && !m_dummyNSView) || (!m_isShown && m_dummyNSView),wxT("wxWindow: m_isShown does not agree with m_dummyNSView"));
699 // Return false if there isn't a window to show or hide
700 NSView *cocoaView = GetNSViewForHiding();
705 // If state isn't changing, return false
708 CocoaReplaceView(m_cocoaHider->GetNSView(), cocoaView);
709 wxASSERT(![m_cocoaHider->GetNSView() superview]);
712 wxASSERT([cocoaView superview]);
716 // If state isn't changing, return false
719 m_cocoaHider = new wxWindowCocoaHider(this);
720 // NOTE: replaceSubview:with will cause m_cocaNSView to be
721 // (auto)released which balances out addSubview
722 CocoaReplaceView(cocoaView, m_cocoaHider->GetNSView());
723 // m_coocaNSView is now only retained by us
724 wxASSERT([m_cocoaHider->GetNSView() superview]);
725 wxASSERT(![cocoaView superview]);
731 void wxWindowCocoa::DoSetSize(int x, int y, int width, int height, int sizeFlags)
733 wxLogTrace(wxTRACE_COCOA_Window_Size,wxT("wxWindow=%p::DoSetSizeWindow(%d,%d,%d,%d,Auto: %s%s)"),this,x,y,width,height,(sizeFlags&wxSIZE_AUTO_WIDTH)?"W":".",sizeFlags&wxSIZE_AUTO_HEIGHT?"H":".");
734 int currentX, currentY;
735 int currentW, currentH;
736 DoGetPosition(¤tX, ¤tY);
737 DoGetSize(¤tW, ¤tH);
738 if((x==-1) && !(sizeFlags&wxSIZE_ALLOW_MINUS_ONE))
740 if((y==-1) && !(sizeFlags&wxSIZE_ALLOW_MINUS_ONE))
743 AdjustForParentClientOrigin(x,y,sizeFlags);
745 wxSize size(wxDefaultSize);
747 if((width==-1)&&!(sizeFlags&wxSIZE_ALLOW_MINUS_ONE))
749 if(sizeFlags&wxSIZE_AUTO_WIDTH)
751 size=DoGetBestSize();
757 if((height==-1)&&!(sizeFlags&wxSIZE_ALLOW_MINUS_ONE))
759 if(sizeFlags&wxSIZE_AUTO_HEIGHT)
762 size=DoGetBestSize();
768 DoMoveWindow(x,y,width,height);
773 void wxWindowCocoa::DoSetToolTip( wxToolTip *tip )
775 wxWindowBase::DoSetToolTip(tip);
779 m_tooltip->SetWindow((wxWindow *)this);
785 void wxWindowCocoa::DoMoveWindow(int x, int y, int width, int height)
787 wxAutoNSAutoreleasePool pool;
788 wxLogTrace(wxTRACE_COCOA_Window_Size,wxT("wxWindow=%p::DoMoveWindow(%d,%d,%d,%d)"),this,x,y,width,height);
790 NSView *nsview = GetNSViewForSuperview();
791 NSView *superview = [nsview superview];
793 wxCHECK_RET(GetParent(), wxT("Window can only be placed correctly when it has a parent"));
795 NSRect oldFrameRect = [nsview frame];
796 NSRect newFrameRect = GetParent()->CocoaTransformWxToBounds(NSMakeRect(x,y,width,height));
797 [nsview setFrame:newFrameRect];
798 // Be sure to redraw the parent to reflect the changed position
799 [superview setNeedsDisplayInRect:oldFrameRect];
800 [superview setNeedsDisplayInRect:newFrameRect];
803 void wxWindowCocoa::SetInitialFrameRect(const wxPoint& pos, const wxSize& size)
805 NSView *nsview = GetNSViewForSuperview();
806 NSView *superview = [nsview superview];
807 wxCHECK_RET(superview,wxT("NSView does not have a superview"));
808 wxCHECK_RET(GetParent(), wxT("Window can only be placed correctly when it has a parent"));
809 NSRect frameRect = [nsview frame];
811 frameRect.size.width = size.x;
813 frameRect.size.height = size.y;
814 frameRect.origin.x = pos.x;
815 frameRect.origin.y = pos.y;
816 // Tell Cocoa to change the margin between the bottom of the superview
817 // and the bottom of the control. Keeps the control pinned to the top
818 // of its superview so that its position in the wxWidgets coordinate
819 // system doesn't change.
820 if(![superview isFlipped])
821 [nsview setAutoresizingMask: NSViewMinYMargin];
822 // MUST set the mask before setFrame: which can generate a size event
823 // and cause a scroller to be added!
824 frameRect = GetParent()->CocoaTransformWxToBounds(frameRect);
825 [nsview setFrame: frameRect];
829 void wxWindow::DoGetSize(int *w, int *h) const
831 NSRect cocoaRect = [GetNSViewForSuperview() frame];
833 *w=(int)cocoaRect.size.width;
835 *h=(int)cocoaRect.size.height;
836 wxLogTrace(wxTRACE_COCOA_Window_Size,wxT("wxWindow=%p::DoGetSize = (%d,%d)"),this,(int)cocoaRect.size.width,(int)cocoaRect.size.height);
839 void wxWindow::DoGetPosition(int *x, int *y) const
841 NSView *nsview = GetNSViewForSuperview();
843 NSRect cocoaRect = [nsview frame];
844 NSRect rectWx = GetParent()->CocoaTransformBoundsToWx(cocoaRect);
846 *x=(int)rectWx.origin.x;
848 *y=(int)rectWx.origin.y;
849 wxLogTrace(wxTRACE_COCOA_Window_Size,wxT("wxWindow=%p::DoGetPosition = (%d,%d)"),this,(int)cocoaRect.origin.x,(int)cocoaRect.origin.y);
852 WXWidget wxWindow::GetHandle() const
854 return m_cocoaNSView;
857 wxWindow* wxWindow::GetWxWindow() const
859 return (wxWindow*) this;
862 void wxWindow::Refresh(bool eraseBack, const wxRect *rect)
864 [m_cocoaNSView setNeedsDisplay:YES];
867 void wxWindow::SetFocus()
869 if([GetNSView() acceptsFirstResponder])
870 [[GetNSView() window] makeFirstResponder: GetNSView()];
873 void wxWindow::DoCaptureMouse()
876 sm_capturedWindow = this;
879 void wxWindow::DoReleaseMouse()
882 sm_capturedWindow = NULL;
885 void wxWindow::DoScreenToClient(int *x, int *y) const
890 void wxWindow::DoClientToScreen(int *x, int *y) const
895 // Get size *available for subwindows* i.e. excluding menu bar etc.
896 void wxWindow::DoGetClientSize(int *x, int *y) const
898 wxLogTrace(wxTRACE_COCOA,wxT("DoGetClientSize:"));
899 if(m_wxCocoaScrollView)
900 m_wxCocoaScrollView->DoGetClientSize(x,y);
902 wxWindowCocoa::DoGetSize(x,y);
905 void wxWindow::DoSetClientSize(int width, int height)
907 wxLogTrace(wxTRACE_COCOA_Window_Size,wxT("DoSetClientSize=(%d,%d)"),width,height);
908 if(m_wxCocoaScrollView)
909 m_wxCocoaScrollView->ClientSizeToSize(width,height);
910 CocoaSetWxWindowSize(width,height);
913 void wxWindow::CocoaSetWxWindowSize(int width, int height)
915 wxWindowCocoa::DoSetSize(wxDefaultCoord,wxDefaultCoord,width,height,wxSIZE_USE_EXISTING);
918 void wxWindow::SetLabel(const wxString& WXUNUSED(label))
920 // Intentional no-op.
923 wxString wxWindow::GetLabel() const
925 // General Get/Set of labels is implemented in wxControlBase
926 wxLogDebug(wxT("wxWindow::GetLabel: Should be overridden if needed."));
927 return wxEmptyString;
930 int wxWindow::GetCharHeight() const
936 int wxWindow::GetCharWidth() const
942 void wxWindow::GetTextExtent(const wxString& string, int *x, int *y,
943 int *descent, int *externalLeading, const wxFont *theFont) const
948 // Coordinates relative to the window
949 void wxWindow::WarpPointer (int x_pos, int y_pos)
954 int wxWindow::GetScrollPos(int orient) const
960 // This now returns the whole range, not just the number
961 // of positions that we can scroll.
962 int wxWindow::GetScrollRange(int orient) const
968 int wxWindow::GetScrollThumb(int orient) const
974 void wxWindow::SetScrollPos(int orient, int pos, bool refresh)
979 void wxWindow::CocoaCreateNSScrollView()
981 if(!m_wxCocoaScrollView)
983 m_wxCocoaScrollView = new wxWindowCocoaScrollView(this);
987 // New function that will replace some of the above.
988 void wxWindow::SetScrollbar(int orient, int pos, int thumbVisible,
989 int range, bool refresh)
991 CocoaCreateNSScrollView();
995 // Does a physical scroll
996 void wxWindow::ScrollWindow(int dx, int dy, const wxRect *rect)
1001 void wxWindow::DoSetVirtualSize( int x, int y )
1003 wxWindowBase::DoSetVirtualSize(x,y);
1004 CocoaCreateNSScrollView();
1005 [m_cocoaNSView setFrameSize:NSMakeSize(m_virtualSize.x,m_virtualSize.y)];
1008 bool wxWindow::SetFont(const wxFont& font)
1014 static int CocoaRaiseWindowCompareFunction(id first, id second, void *target)
1016 // first should be ordered higher
1018 return NSOrderedDescending;
1019 // second should be ordered higher
1021 return NSOrderedAscending;
1022 return NSOrderedSame;
1025 // Raise the window to the top of the Z order
1026 void wxWindow::Raise()
1028 // wxAutoNSAutoreleasePool pool;
1029 NSView *nsview = GetNSViewForSuperview();
1030 [[nsview superview] sortSubviewsUsingFunction:
1031 CocoaRaiseWindowCompareFunction
1035 static int CocoaLowerWindowCompareFunction(id first, id second, void *target)
1037 // first should be ordered lower
1039 return NSOrderedAscending;
1040 // second should be ordered lower
1042 return NSOrderedDescending;
1043 return NSOrderedSame;
1046 // Lower the window to the bottom of the Z order
1047 void wxWindow::Lower()
1049 NSView *nsview = GetNSViewForSuperview();
1050 [[nsview superview] sortSubviewsUsingFunction:
1051 CocoaLowerWindowCompareFunction
1055 bool wxWindow::DoPopupMenu(wxMenu *menu, int x, int y)
1060 // Get the window with the focus
1061 wxWindow *wxWindowBase::DoFindFocus()
1063 // Basically we are somewhat emulating the responder chain here except
1064 // we are only loking for the first responder in the key window or
1065 // upon failing to find one if the main window is different we look
1066 // for the first responder in the main window.
1068 // Note that the firstResponder doesn't necessarily have to be an
1069 // NSView but wxCocoaNSView::GetFromCocoa() will simply return
1070 // NULL unless it finds its argument in its hash map.
1074 NSWindow *keyWindow = [[NSApplication sharedApplication] keyWindow];
1075 win = wxCocoaNSView::GetFromCocoa(static_cast<NSView*>([keyWindow firstResponder]));
1077 return win->GetWxWindow();
1079 NSWindow *mainWindow = [[NSApplication sharedApplication] keyWindow];
1080 if(mainWindow == keyWindow)
1082 win = wxCocoaNSView::GetFromCocoa(static_cast<NSView*>([mainWindow firstResponder]));
1084 return win->GetWxWindow();
1089 /* static */ wxWindow *wxWindowBase::GetCapture()
1092 return wxWindowCocoa::sm_capturedWindow;
1095 wxWindow *wxGetActiveWindow()
1101 wxPoint wxGetMousePosition()
1104 return wxDefaultPosition;
1107 wxMouseState wxGetMouseState()
1114 wxWindow* wxFindWindowAtPointer(wxPoint& pt)
1116 pt = wxGetMousePosition();
1121 // ========================================================================
1122 // wxCocoaTrackingRectManager
1123 // ========================================================================
1125 wxCocoaTrackingRectManager::wxCocoaTrackingRectManager(wxWindow *window)
1128 m_isTrackingRectActive = false;
1129 m_runLoopObserver = NULL;
1130 BuildTrackingRect();
1133 void wxCocoaTrackingRectManager::ClearTrackingRect()
1135 if(m_isTrackingRectActive)
1137 [m_window->GetNSView() removeTrackingRect:m_trackingRectTag];
1138 m_isTrackingRectActive = false;
1140 // If we were doing periodic events we need to clear those too
1141 StopSynthesizingEvents();
1144 void wxCocoaTrackingRectManager::StopSynthesizingEvents()
1146 if(m_runLoopObserver != NULL)
1148 CFRunLoopRemoveObserver([[NSRunLoop currentRunLoop] getCFRunLoop], m_runLoopObserver, kCFRunLoopCommonModes);
1149 CFRelease(m_runLoopObserver);
1150 m_runLoopObserver = NULL;
1154 void wxCocoaTrackingRectManager::BuildTrackingRect()
1156 wxASSERT_MSG(!m_isTrackingRectActive, wxT("Tracking rect was not cleared"));
1157 if([m_window->GetNSView() window] != nil)
1159 m_trackingRectTag = [m_window->GetNSView() addTrackingRect:[m_window->GetNSView() visibleRect] owner:m_window->GetNSView() userData:NULL assumeInside:NO];
1160 m_isTrackingRectActive = true;
1164 static NSPoint s_lastScreenMouseLocation = NSZeroPoint;
1166 static void SynthesizeMouseMovedEvent(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info)
1168 NSPoint screenMouseLocation = [NSEvent mouseLocation];
1169 if(screenMouseLocation.x != s_lastScreenMouseLocation.x || screenMouseLocation.y != s_lastScreenMouseLocation.y)
1171 wxCocoaNSView *win = reinterpret_cast<wxCocoaNSView*>(info);
1172 win->Cocoa_synthesizeMouseMoved();
1176 void wxCocoaTrackingRectManager::BeginSynthesizingEvents()
1178 CFRunLoopObserverContext observerContext =
1180 , static_cast<wxCocoaNSView*>(m_window)
1185 m_runLoopObserver = CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopBeforeWaiting, TRUE, 0, SynthesizeMouseMovedEvent, &observerContext);
1186 CFRunLoopAddObserver([[NSRunLoop currentRunLoop] getCFRunLoop], m_runLoopObserver, kCFRunLoopCommonModes);
1189 void wxCocoaTrackingRectManager::RebuildTrackingRect()
1191 ClearTrackingRect();
1192 BuildTrackingRect();
1195 wxCocoaTrackingRectManager::~wxCocoaTrackingRectManager()
1197 ClearTrackingRect();
1200 bool wxCocoaTrackingRectManager::IsOwnerOfEvent(NSEvent *anEvent)
1202 return m_isTrackingRectActive && (m_trackingRectTag == [anEvent trackingNumber]);