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 /* NSComparisonResult is typedef'd as an enum pre-Leopard but typedef'd as
45 * NSInteger post-Leopard. Pre-Leopard the Cocoa toolkit expects a function
46 * returning int and not NSComparisonResult. Post-Leopard the Cocoa toolkit
47 * expects a function returning the new non-enum NSComparsionResult.
48 * Hence we create a typedef named CocoaWindowCompareFunctionResult.
50 #if defined(NSINTEGER_DEFINED)
51 typedef NSComparisonResult CocoaWindowCompareFunctionResult;
53 typedef int CocoaWindowCompareFunctionResult;
56 // A category for methods that are only present in Panther's SDK
57 @interface NSView(wxNSViewPrePantherCompatibility)
58 - (void)getRectsBeingDrawn:(const NSRect **)rects count:(int *)count;
61 NSPoint CocoaTransformNSViewBoundsToWx(NSView *nsview, NSPoint pointBounds)
63 wxCHECK_MSG(nsview, pointBounds, wxT("Need to have a Cocoa view to do translation"));
64 if([nsview isFlipped])
66 NSRect ourBounds = [nsview bounds];
69 , ourBounds.size.height - pointBounds.y
73 NSRect CocoaTransformNSViewBoundsToWx(NSView *nsview, NSRect rectBounds)
75 wxCHECK_MSG(nsview, rectBounds, wxT("Need to have a Cocoa view to do translation"));
76 if([nsview isFlipped])
78 NSRect ourBounds = [nsview bounds];
81 , ourBounds.size.height - (rectBounds.origin.y + rectBounds.size.height)
82 , rectBounds.size.width
83 , rectBounds.size.height
87 NSPoint CocoaTransformNSViewWxToBounds(NSView *nsview, NSPoint pointWx)
89 wxCHECK_MSG(nsview, pointWx, wxT("Need to have a Cocoa view to do translation"));
90 if([nsview isFlipped])
92 NSRect ourBounds = [nsview bounds];
95 , ourBounds.size.height - pointWx.y
99 NSRect CocoaTransformNSViewWxToBounds(NSView *nsview, NSRect rectWx)
101 wxCHECK_MSG(nsview, rectWx, wxT("Need to have a Cocoa view to do translation"));
102 if([nsview isFlipped])
104 NSRect ourBounds = [nsview bounds];
107 , ourBounds.size.height - (rectWx.origin.y + rectWx.size.height)
113 // ========================================================================
114 // wxWindowCocoaHider
115 // ========================================================================
116 class wxWindowCocoaHider: protected wxCocoaNSView
118 DECLARE_NO_COPY_CLASS(wxWindowCocoaHider)
120 wxWindowCocoaHider(wxWindow *owner);
121 virtual ~wxWindowCocoaHider();
122 inline WX_NSView GetNSView() { return m_dummyNSView; }
124 wxWindowCocoa *m_owner;
125 WX_NSView m_dummyNSView;
126 virtual void Cocoa_FrameChanged(void);
127 virtual void Cocoa_synthesizeMouseMoved(void) {}
128 #ifdef WXCOCOA_FILL_DUMMY_VIEW
129 virtual bool Cocoa_drawRect(const NSRect& rect);
130 #endif //def WXCOCOA_FILL_DUMMY_VIEW
132 wxWindowCocoaHider();
135 // ========================================================================
136 // wxWindowCocoaScrollView
137 // ========================================================================
138 class wxWindowCocoaScrollView: protected wxCocoaNSView
140 DECLARE_NO_COPY_CLASS(wxWindowCocoaScrollView)
142 wxWindowCocoaScrollView(wxWindow *owner);
143 virtual ~wxWindowCocoaScrollView();
144 inline WX_NSScrollView GetNSScrollView() { return m_cocoaNSScrollView; }
145 void ClientSizeToSize(int &width, int &height);
146 void DoGetClientSize(int *x, int *y) const;
148 void Unencapsulate();
150 wxWindowCocoa *m_owner;
151 WX_NSScrollView m_cocoaNSScrollView;
152 virtual void Cocoa_FrameChanged(void);
153 virtual void Cocoa_synthesizeMouseMoved(void) {}
155 wxWindowCocoaScrollView();
158 // ========================================================================
160 // ========================================================================
161 @interface wxDummyNSView : NSView
162 - (NSView *)hitTest:(NSPoint)aPoint;
164 WX_DECLARE_GET_OBJC_CLASS(wxDummyNSView,NSView)
166 @implementation wxDummyNSView : NSView
167 - (NSView *)hitTest:(NSPoint)aPoint
173 WX_IMPLEMENT_GET_OBJC_CLASS(wxDummyNSView,NSView)
175 // ========================================================================
176 // wxWindowCocoaHider
177 // ========================================================================
178 wxWindowCocoaHider::wxWindowCocoaHider(wxWindow *owner)
182 wxASSERT(owner->GetNSViewForHiding());
183 m_dummyNSView = [[WX_GET_OBJC_CLASS(wxDummyNSView) alloc]
184 initWithFrame:[owner->GetNSViewForHiding() frame]];
185 [m_dummyNSView setAutoresizingMask: [owner->GetNSViewForHiding() autoresizingMask]];
186 AssociateNSView(m_dummyNSView);
189 wxWindowCocoaHider::~wxWindowCocoaHider()
191 DisassociateNSView(m_dummyNSView);
192 [m_dummyNSView release];
195 void wxWindowCocoaHider::Cocoa_FrameChanged(void)
197 // Keep the real window in synch with the dummy
198 wxASSERT(m_dummyNSView);
199 [m_owner->GetNSViewForHiding() setFrame:[m_dummyNSView frame]];
203 #ifdef WXCOCOA_FILL_DUMMY_VIEW
204 bool wxWindowCocoaHider::Cocoa_drawRect(const NSRect& rect)
206 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:rect];
207 [[NSColor greenColor] set];
212 #endif //def WXCOCOA_FILL_DUMMY_VIEW
214 // ========================================================================
215 // wxFlippedNSClipView
216 // ========================================================================
217 @interface wxFlippedNSClipView : NSClipView
220 WX_DECLARE_GET_OBJC_CLASS(wxFlippedNSClipView,NSClipView)
222 @implementation wxFlippedNSClipView : NSClipView
229 WX_IMPLEMENT_GET_OBJC_CLASS(wxFlippedNSClipView,NSClipView)
231 // ========================================================================
232 // wxWindowCocoaScrollView
233 // ========================================================================
234 wxWindowCocoaScrollView::wxWindowCocoaScrollView(wxWindow *owner)
237 wxAutoNSAutoreleasePool pool;
239 wxASSERT(owner->GetNSView());
240 m_cocoaNSScrollView = [[NSScrollView alloc]
241 initWithFrame:[owner->GetNSView() frame]];
242 AssociateNSView(m_cocoaNSScrollView);
244 /* Replace the default NSClipView with a flipped one. This ensures
245 scrolling is "pinned" to the top-left instead of bottom-right. */
246 NSClipView *flippedClip = [[WX_GET_OBJC_CLASS(wxFlippedNSClipView) alloc]
247 initWithFrame: [[m_cocoaNSScrollView contentView] frame]];
248 [m_cocoaNSScrollView setContentView:flippedClip];
249 [flippedClip release];
251 [m_cocoaNSScrollView setBackgroundColor: [NSColor windowBackgroundColor]];
252 [m_cocoaNSScrollView setHasHorizontalScroller: YES];
253 [m_cocoaNSScrollView setHasVerticalScroller: YES];
257 void wxWindowCocoaScrollView::Encapsulate()
259 // Set the scroll view autoresizingMask to match the current NSView
260 [m_cocoaNSScrollView setAutoresizingMask: [m_owner->GetNSView() autoresizingMask]];
261 [m_owner->GetNSView() setAutoresizingMask: NSViewNotSizable];
262 // NOTE: replaceSubView will cause m_cocaNSView to be released
263 // except when it hasn't been added into an NSView hierarchy in which
264 // case it doesn't need to be and this should work out to a no-op
265 m_owner->CocoaReplaceView(m_owner->GetNSView(), m_cocoaNSScrollView);
266 // The NSView is still retained by owner
267 [m_cocoaNSScrollView setDocumentView: m_owner->GetNSView()];
268 // Now it's also retained by the NSScrollView
271 void wxWindowCocoaScrollView::Unencapsulate()
273 [m_cocoaNSScrollView setDocumentView: nil];
274 m_owner->CocoaReplaceView(m_cocoaNSScrollView, m_owner->GetNSView());
275 if(![[m_owner->GetNSView() superview] isFlipped])
276 [m_owner->GetNSView() setAutoresizingMask: NSViewMinYMargin];
279 wxWindowCocoaScrollView::~wxWindowCocoaScrollView()
281 DisassociateNSView(m_cocoaNSScrollView);
282 [m_cocoaNSScrollView release];
285 void wxWindowCocoaScrollView::ClientSizeToSize(int &width, int &height)
287 NSSize frameSize = [NSScrollView
288 frameSizeForContentSize: NSMakeSize(width,height)
289 hasHorizontalScroller: [m_cocoaNSScrollView hasHorizontalScroller]
290 hasVerticalScroller: [m_cocoaNSScrollView hasVerticalScroller]
291 borderType: [m_cocoaNSScrollView borderType]];
292 width = (int)frameSize.width;
293 height = (int)frameSize.height;
296 void wxWindowCocoaScrollView::DoGetClientSize(int *x, int *y) const
298 NSSize nssize = [m_cocoaNSScrollView contentSize];
300 *x = (int)nssize.width;
302 *y = (int)nssize.height;
305 void wxWindowCocoaScrollView::Cocoa_FrameChanged(void)
307 wxLogTrace(wxTRACE_COCOA,wxT("Cocoa_FrameChanged"));
308 wxSizeEvent event(m_owner->GetSize(), m_owner->GetId());
309 event.SetEventObject(m_owner);
310 m_owner->GetEventHandler()->ProcessEvent(event);
313 // ========================================================================
315 // ========================================================================
316 // normally the base classes aren't included, but wxWindow is special
317 #ifdef __WXUNIVERSAL__
318 IMPLEMENT_ABSTRACT_CLASS(wxWindowCocoa, wxWindowBase)
320 IMPLEMENT_DYNAMIC_CLASS(wxWindow, wxWindowBase)
323 BEGIN_EVENT_TABLE(wxWindowCocoa, wxWindowBase)
326 wxWindow *wxWindowCocoa::sm_capturedWindow = NULL;
329 void wxWindowCocoa::Init()
331 m_cocoaNSView = NULL;
333 m_wxCocoaScrollView = NULL;
334 m_isBeingDeleted = false;
336 m_visibleTrackingRectManager = NULL;
340 bool wxWindow::Create(wxWindow *parent, wxWindowID winid,
344 const wxString& name)
346 if(!CreateBase(parent,winid,pos,size,style,wxDefaultValidator,name))
349 // TODO: create the window
350 m_cocoaNSView = NULL;
351 SetNSView([[WX_GET_OBJC_CLASS(WXNSView) alloc] initWithFrame: MakeDefaultNSRect(size)]);
352 [m_cocoaNSView release];
356 m_parent->AddChild(this);
357 m_parent->CocoaAddChild(this);
358 SetInitialFrameRect(pos,size);
365 wxWindow::~wxWindow()
367 wxAutoNSAutoreleasePool pool;
370 // Make sure our parent (in the wxWidgets sense) is our superview
371 // before we go removing from it.
372 if(m_parent && m_parent->GetNSView()==[GetNSViewForSuperview() superview])
373 CocoaRemoveFromParent();
375 delete m_wxCocoaScrollView;
381 void wxWindowCocoa::CocoaAddChild(wxWindowCocoa *child)
383 // Pool here due to lack of one during wx init phase
384 wxAutoNSAutoreleasePool pool;
386 NSView *childView = child->GetNSViewForSuperview();
389 [m_cocoaNSView addSubview: childView];
390 child->m_isShown = !m_cocoaHider;
393 void wxWindowCocoa::CocoaRemoveFromParent(void)
395 [GetNSViewForSuperview() removeFromSuperview];
398 void wxWindowCocoa::SetNSView(WX_NSView cocoaNSView)
400 // Clear the visible area tracking rect if we have one.
401 delete m_visibleTrackingRectManager;
402 m_visibleTrackingRectManager = NULL;
404 bool need_debug = cocoaNSView || m_cocoaNSView;
405 if(need_debug) wxLogTrace(wxTRACE_COCOA_RetainRelease,wxT("wxWindowCocoa=%p::SetNSView [m_cocoaNSView=%p retainCount]=%d"),this,m_cocoaNSView,[m_cocoaNSView retainCount]);
406 DisassociateNSView(m_cocoaNSView);
407 [cocoaNSView retain];
408 [m_cocoaNSView release];
409 m_cocoaNSView = cocoaNSView;
410 AssociateNSView(m_cocoaNSView);
411 if(need_debug) wxLogTrace(wxTRACE_COCOA_RetainRelease,wxT("wxWindowCocoa=%p::SetNSView [cocoaNSView=%p retainCount]=%d"),this,cocoaNSView,[cocoaNSView retainCount]);
414 WX_NSView wxWindowCocoa::GetNSViewForSuperview() const
417 ? m_cocoaHider->GetNSView()
418 : m_wxCocoaScrollView
419 ? m_wxCocoaScrollView->GetNSScrollView()
423 WX_NSView wxWindowCocoa::GetNSViewForHiding() const
425 return m_wxCocoaScrollView
426 ? m_wxCocoaScrollView->GetNSScrollView()
430 NSPoint wxWindowCocoa::CocoaTransformBoundsToWx(NSPoint pointBounds)
432 // TODO: Handle scrolling offset
433 return CocoaTransformNSViewBoundsToWx(GetNSView(), pointBounds);
436 NSRect wxWindowCocoa::CocoaTransformBoundsToWx(NSRect rectBounds)
438 // TODO: Handle scrolling offset
439 return CocoaTransformNSViewBoundsToWx(GetNSView(), rectBounds);
442 NSPoint wxWindowCocoa::CocoaTransformWxToBounds(NSPoint pointWx)
444 // TODO: Handle scrolling offset
445 return CocoaTransformNSViewWxToBounds(GetNSView(), pointWx);
448 NSRect wxWindowCocoa::CocoaTransformWxToBounds(NSRect rectWx)
450 // TODO: Handle scrolling offset
451 return CocoaTransformNSViewWxToBounds(GetNSView(), rectWx);
454 WX_NSAffineTransform wxWindowCocoa::CocoaGetWxToBoundsTransform()
456 // TODO: Handle scrolling offset
457 NSAffineTransform *transform = wxDC::CocoaGetWxToBoundsTransform([GetNSView() isFlipped], [GetNSView() bounds].size.height);
461 bool wxWindowCocoa::Cocoa_drawRect(const NSRect &rect)
463 wxLogTrace(wxTRACE_COCOA,wxT("Cocoa_drawRect"));
464 // Recursion can happen if the event loop runs from within the paint
465 // handler. For instance, if an assertion dialog is shown.
466 // FIXME: This seems less than ideal.
469 wxLogDebug(wxT("Paint event recursion!"));
474 // Set m_updateRegion
475 const NSRect *rects = ▭ // The bounding box of the region
476 NSInteger countRects = 1;
477 // Try replacing the larger rectangle with a list of smaller ones:
478 if ([GetNSView() respondsToSelector:@selector(getRectsBeingDrawn:count:)])
479 [GetNSView() getRectsBeingDrawn:&rects count:&countRects];
481 NSRect *transformedRects = (NSRect*)malloc(sizeof(NSRect)*countRects);
482 for(int i=0; i<countRects; i++)
484 transformedRects[i] = CocoaTransformBoundsToWx(rects[i]);
486 m_updateRegion = wxRegion(transformedRects,countRects);
487 free(transformedRects);
489 wxPaintEvent event(m_windowId);
490 event.SetEventObject(this);
491 bool ret = GetEventHandler()->ProcessEvent(event);
496 void wxWindowCocoa::InitMouseEvent(wxMouseEvent& event, WX_NSEvent cocoaEvent)
498 wxASSERT_MSG([m_cocoaNSView window]==[cocoaEvent window],wxT("Mouse event for different NSWindow"));
499 // Mouse events happen at the NSWindow level so we need to convert
500 // into our bounds coordinates then convert to wx coordinates.
501 NSPoint cocoaPoint = [m_cocoaNSView convertPoint:[(NSEvent*)cocoaEvent locationInWindow] fromView:nil];
502 NSPoint pointWx = CocoaTransformBoundsToWx(cocoaPoint);
503 // FIXME: Should we be adjusting for client area origin?
504 const wxPoint &clientorigin = GetClientAreaOrigin();
505 event.m_x = (wxCoord)pointWx.x - clientorigin.x;
506 event.m_y = (wxCoord)pointWx.y - clientorigin.y;
508 event.m_shiftDown = [cocoaEvent modifierFlags] & NSShiftKeyMask;
509 event.m_controlDown = [cocoaEvent modifierFlags] & NSControlKeyMask;
510 event.m_altDown = [cocoaEvent modifierFlags] & NSAlternateKeyMask;
511 event.m_metaDown = [cocoaEvent modifierFlags] & NSCommandKeyMask;
513 // TODO: set timestamp?
514 event.SetEventObject(this);
515 event.SetId(GetId());
518 bool wxWindowCocoa::Cocoa_mouseMoved(WX_NSEvent theEvent)
520 wxMouseEvent event(wxEVT_MOTION);
521 InitMouseEvent(event,theEvent);
522 wxLogTrace(wxTRACE_COCOA,wxT("wxWindow=%p::Cocoa_mouseMoved @%d,%d"),this,event.m_x,event.m_y);
523 return GetEventHandler()->ProcessEvent(event);
526 void wxWindowCocoa::Cocoa_synthesizeMouseMoved()
528 wxMouseEvent event(wxEVT_MOTION);
529 NSWindow *window = [GetNSView() window];
530 NSPoint locationInWindow = [window mouseLocationOutsideOfEventStream];
531 NSPoint cocoaPoint = [m_cocoaNSView convertPoint:locationInWindow fromView:nil];
533 NSPoint pointWx = CocoaTransformBoundsToWx(cocoaPoint);
534 // FIXME: Should we be adjusting for client area origin?
535 const wxPoint &clientorigin = GetClientAreaOrigin();
536 event.m_x = (wxCoord)pointWx.x - clientorigin.x;
537 event.m_y = (wxCoord)pointWx.y - clientorigin.y;
539 // TODO: Handle shift, control, alt, meta flags
540 event.SetEventObject(this);
541 event.SetId(GetId());
543 wxLogTrace(wxTRACE_COCOA,wxT("wxwin=%p Synthesized Mouse Moved @%d,%d"),this,event.m_x,event.m_y);
544 GetEventHandler()->ProcessEvent(event);
547 bool wxWindowCocoa::Cocoa_mouseEntered(WX_NSEvent theEvent)
549 if(m_visibleTrackingRectManager != NULL && m_visibleTrackingRectManager->IsOwnerOfEvent(theEvent))
551 m_visibleTrackingRectManager->BeginSynthesizingEvents();
553 // Although we synthesize the mouse moved events we don't poll for them but rather send them only when
554 // some other event comes in. That other event is (guess what) mouse moved events that will be sent
555 // to the NSWindow which will forward them on to the first responder. We are not likely to be the
556 // first responder, so the mouseMoved: events are effectively discarded.
557 [[GetNSView() window] setAcceptsMouseMovedEvents:YES];
559 wxMouseEvent event(wxEVT_ENTER_WINDOW);
560 InitMouseEvent(event,theEvent);
561 wxLogTrace(wxTRACE_COCOA,wxT("wxwin=%p Mouse Entered @%d,%d"),this,event.m_x,event.m_y);
562 return GetEventHandler()->ProcessEvent(event);
568 bool wxWindowCocoa::Cocoa_mouseExited(WX_NSEvent theEvent)
570 if(m_visibleTrackingRectManager != NULL && m_visibleTrackingRectManager->IsOwnerOfEvent(theEvent))
572 m_visibleTrackingRectManager->StopSynthesizingEvents();
574 wxMouseEvent event(wxEVT_LEAVE_WINDOW);
575 InitMouseEvent(event,theEvent);
576 wxLogTrace(wxTRACE_COCOA,wxT("wxwin=%p Mouse Exited @%d,%d"),this,event.m_x,event.m_y);
577 return GetEventHandler()->ProcessEvent(event);
583 bool wxWindowCocoa::Cocoa_mouseDown(WX_NSEvent theEvent)
585 wxMouseEvent event([theEvent clickCount]<2?wxEVT_LEFT_DOWN:wxEVT_LEFT_DCLICK);
586 InitMouseEvent(event,theEvent);
587 wxLogTrace(wxTRACE_COCOA,wxT("Mouse Down @%d,%d num clicks=%d"),event.m_x,event.m_y,[theEvent clickCount]);
588 return GetEventHandler()->ProcessEvent(event);
591 bool wxWindowCocoa::Cocoa_mouseDragged(WX_NSEvent theEvent)
593 wxMouseEvent event(wxEVT_MOTION);
594 InitMouseEvent(event,theEvent);
595 event.m_leftDown = true;
596 wxLogTrace(wxTRACE_COCOA,wxT("Mouse Drag @%d,%d"),event.m_x,event.m_y);
597 return GetEventHandler()->ProcessEvent(event);
600 bool wxWindowCocoa::Cocoa_mouseUp(WX_NSEvent theEvent)
602 wxMouseEvent event(wxEVT_LEFT_UP);
603 InitMouseEvent(event,theEvent);
604 wxLogTrace(wxTRACE_COCOA,wxT("Mouse Up @%d,%d"),event.m_x,event.m_y);
605 return GetEventHandler()->ProcessEvent(event);
608 bool wxWindowCocoa::Cocoa_rightMouseDown(WX_NSEvent theEvent)
610 wxMouseEvent event([theEvent clickCount]<2?wxEVT_RIGHT_DOWN:wxEVT_RIGHT_DCLICK);
611 InitMouseEvent(event,theEvent);
612 wxLogDebug(wxT("Mouse Down @%d,%d num clicks=%d"),event.m_x,event.m_y,[theEvent clickCount]);
613 return GetEventHandler()->ProcessEvent(event);
616 bool wxWindowCocoa::Cocoa_rightMouseDragged(WX_NSEvent theEvent)
618 wxMouseEvent event(wxEVT_MOTION);
619 InitMouseEvent(event,theEvent);
620 event.m_rightDown = true;
621 wxLogDebug(wxT("Mouse Drag @%d,%d"),event.m_x,event.m_y);
622 return GetEventHandler()->ProcessEvent(event);
625 bool wxWindowCocoa::Cocoa_rightMouseUp(WX_NSEvent theEvent)
627 wxMouseEvent event(wxEVT_RIGHT_UP);
628 InitMouseEvent(event,theEvent);
629 wxLogDebug(wxT("Mouse Up @%d,%d"),event.m_x,event.m_y);
630 return GetEventHandler()->ProcessEvent(event);
633 bool wxWindowCocoa::Cocoa_otherMouseDown(WX_NSEvent theEvent)
638 bool wxWindowCocoa::Cocoa_otherMouseDragged(WX_NSEvent theEvent)
643 bool wxWindowCocoa::Cocoa_otherMouseUp(WX_NSEvent theEvent)
648 void wxWindowCocoa::Cocoa_FrameChanged(void)
650 wxLogTrace(wxTRACE_COCOA,wxT("wxWindow=%p::Cocoa_FrameChanged"),this);
651 if(m_visibleTrackingRectManager != NULL)
652 m_visibleTrackingRectManager->RebuildTrackingRect();
653 wxSizeEvent event(GetSize(), m_windowId);
654 event.SetEventObject(this);
655 GetEventHandler()->ProcessEvent(event);
658 bool wxWindowCocoa::Cocoa_resetCursorRects()
660 wxLogTrace(wxTRACE_COCOA,wxT("wxWindow=%p::Cocoa_resetCursorRects"),this);
661 if(m_visibleTrackingRectManager != NULL)
662 m_visibleTrackingRectManager->RebuildTrackingRect();
664 if(!m_cursor.GetNSCursor())
667 [GetNSView() addCursorRect: [GetNSView() visibleRect] cursor: m_cursor.GetNSCursor()];
672 bool wxWindowCocoa::SetCursor(const wxCursor &cursor)
674 if(!wxWindowBase::SetCursor(cursor))
676 // Invalidate the cursor rects so the cursor will change
677 [[GetNSView() window] invalidateCursorRectsForView:GetNSView()];
681 bool wxWindowCocoa::Cocoa_viewDidMoveToWindow()
683 wxLogTrace(wxTRACE_COCOA,wxT("wxWindow=%p::viewDidMoveToWindow"),this);
684 // Set up new tracking rects. I am reasonably sure the new window must be set before doing this.
685 if(m_visibleTrackingRectManager != NULL)
686 m_visibleTrackingRectManager->BuildTrackingRect();
690 bool wxWindowCocoa::Cocoa_viewWillMoveToWindow(WX_NSWindow newWindow)
692 wxLogTrace(wxTRACE_COCOA,wxT("wxWindow=%p::viewWillMoveToWindow:%p"),this, newWindow);
693 // Clear tracking rects. It is imperative this be done before the new window is set.
694 if(m_visibleTrackingRectManager != NULL)
695 m_visibleTrackingRectManager->ClearTrackingRect();
699 bool wxWindow::Close(bool force)
701 // The only reason this function exists is that it is virtual and
702 // wxTopLevelWindowCocoa will override it.
703 return wxWindowBase::Close(force);
706 void wxWindow::CocoaReplaceView(WX_NSView oldView, WX_NSView newView)
708 [[oldView superview] replaceSubview:oldView with:newView];
711 void wxWindow::DoEnable(bool enable)
713 CocoaSetEnabled(enable);
716 bool wxWindow::Show(bool show)
718 wxAutoNSAutoreleasePool pool;
719 // If the window is marked as visible, then it shouldn't have a dummy view
720 // If the window is marked hidden, then it should have a dummy view
721 // wxSpinCtrl (generic) abuses m_isShown, don't use it for any logic
722 // wxASSERT_MSG( (m_isShown && !m_dummyNSView) || (!m_isShown && m_dummyNSView),wxT("wxWindow: m_isShown does not agree with m_dummyNSView"));
723 // Return false if there isn't a window to show or hide
724 NSView *cocoaView = GetNSViewForHiding();
729 // If state isn't changing, return false
732 CocoaReplaceView(m_cocoaHider->GetNSView(), cocoaView);
733 wxASSERT(![m_cocoaHider->GetNSView() superview]);
736 wxASSERT([cocoaView superview]);
740 // If state isn't changing, return false
743 m_cocoaHider = new wxWindowCocoaHider(this);
744 // NOTE: replaceSubview:with will cause m_cocaNSView to be
745 // (auto)released which balances out addSubview
746 CocoaReplaceView(cocoaView, m_cocoaHider->GetNSView());
747 // m_coocaNSView is now only retained by us
748 wxASSERT([m_cocoaHider->GetNSView() superview]);
749 wxASSERT(![cocoaView superview]);
755 void wxWindowCocoa::DoSetSize(int x, int y, int width, int height, int sizeFlags)
757 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":".");
758 int currentX, currentY;
759 int currentW, currentH;
760 DoGetPosition(¤tX, ¤tY);
761 DoGetSize(¤tW, ¤tH);
762 if((x==-1) && !(sizeFlags&wxSIZE_ALLOW_MINUS_ONE))
764 if((y==-1) && !(sizeFlags&wxSIZE_ALLOW_MINUS_ONE))
767 AdjustForParentClientOrigin(x,y,sizeFlags);
769 wxSize size(wxDefaultSize);
771 if((width==-1)&&!(sizeFlags&wxSIZE_ALLOW_MINUS_ONE))
773 if(sizeFlags&wxSIZE_AUTO_WIDTH)
775 size=DoGetBestSize();
781 if((height==-1)&&!(sizeFlags&wxSIZE_ALLOW_MINUS_ONE))
783 if(sizeFlags&wxSIZE_AUTO_HEIGHT)
786 size=DoGetBestSize();
792 DoMoveWindow(x,y,width,height);
797 void wxWindowCocoa::DoSetToolTip( wxToolTip *tip )
799 wxWindowBase::DoSetToolTip(tip);
803 m_tooltip->SetWindow((wxWindow *)this);
809 void wxWindowCocoa::DoMoveWindow(int x, int y, int width, int height)
811 wxAutoNSAutoreleasePool pool;
812 wxLogTrace(wxTRACE_COCOA_Window_Size,wxT("wxWindow=%p::DoMoveWindow(%d,%d,%d,%d)"),this,x,y,width,height);
814 NSView *nsview = GetNSViewForSuperview();
815 NSView *superview = [nsview superview];
817 wxCHECK_RET(GetParent(), wxT("Window can only be placed correctly when it has a parent"));
819 NSRect oldFrameRect = [nsview frame];
820 NSRect newFrameRect = GetParent()->CocoaTransformWxToBounds(NSMakeRect(x,y,width,height));
821 [nsview setFrame:newFrameRect];
822 // Be sure to redraw the parent to reflect the changed position
823 [superview setNeedsDisplayInRect:oldFrameRect];
824 [superview setNeedsDisplayInRect:newFrameRect];
827 void wxWindowCocoa::SetInitialFrameRect(const wxPoint& pos, const wxSize& size)
829 NSView *nsview = GetNSViewForSuperview();
830 NSView *superview = [nsview superview];
831 wxCHECK_RET(superview,wxT("NSView does not have a superview"));
832 wxCHECK_RET(GetParent(), wxT("Window can only be placed correctly when it has a parent"));
833 NSRect frameRect = [nsview frame];
835 frameRect.size.width = size.x;
837 frameRect.size.height = size.y;
838 frameRect.origin.x = pos.x;
839 frameRect.origin.y = pos.y;
840 // Tell Cocoa to change the margin between the bottom of the superview
841 // and the bottom of the control. Keeps the control pinned to the top
842 // of its superview so that its position in the wxWidgets coordinate
843 // system doesn't change.
844 if(![superview isFlipped])
845 [nsview setAutoresizingMask: NSViewMinYMargin];
846 // MUST set the mask before setFrame: which can generate a size event
847 // and cause a scroller to be added!
848 frameRect = GetParent()->CocoaTransformWxToBounds(frameRect);
849 [nsview setFrame: frameRect];
853 void wxWindow::DoGetSize(int *w, int *h) const
855 NSRect cocoaRect = [GetNSViewForSuperview() frame];
857 *w=(int)cocoaRect.size.width;
859 *h=(int)cocoaRect.size.height;
860 wxLogTrace(wxTRACE_COCOA_Window_Size,wxT("wxWindow=%p::DoGetSize = (%d,%d)"),this,(int)cocoaRect.size.width,(int)cocoaRect.size.height);
863 void wxWindow::DoGetPosition(int *x, int *y) const
865 NSView *nsview = GetNSViewForSuperview();
867 NSRect cocoaRect = [nsview frame];
868 NSRect rectWx = GetParent()->CocoaTransformBoundsToWx(cocoaRect);
870 *x=(int)rectWx.origin.x;
872 *y=(int)rectWx.origin.y;
873 wxLogTrace(wxTRACE_COCOA_Window_Size,wxT("wxWindow=%p::DoGetPosition = (%d,%d)"),this,(int)cocoaRect.origin.x,(int)cocoaRect.origin.y);
876 WXWidget wxWindow::GetHandle() const
878 return m_cocoaNSView;
881 wxWindow* wxWindow::GetWxWindow() const
883 return (wxWindow*) this;
886 void wxWindow::Refresh(bool eraseBack, const wxRect *rect)
888 [m_cocoaNSView setNeedsDisplay:YES];
891 void wxWindow::SetFocus()
893 if([GetNSView() acceptsFirstResponder])
894 [[GetNSView() window] makeFirstResponder: GetNSView()];
897 void wxWindow::DoCaptureMouse()
900 sm_capturedWindow = this;
903 void wxWindow::DoReleaseMouse()
906 sm_capturedWindow = NULL;
909 void wxWindow::DoScreenToClient(int *x, int *y) const
914 void wxWindow::DoClientToScreen(int *x, int *y) const
919 // Get size *available for subwindows* i.e. excluding menu bar etc.
920 void wxWindow::DoGetClientSize(int *x, int *y) const
922 wxLogTrace(wxTRACE_COCOA,wxT("DoGetClientSize:"));
923 if(m_wxCocoaScrollView)
924 m_wxCocoaScrollView->DoGetClientSize(x,y);
926 wxWindowCocoa::DoGetSize(x,y);
929 void wxWindow::DoSetClientSize(int width, int height)
931 wxLogTrace(wxTRACE_COCOA_Window_Size,wxT("DoSetClientSize=(%d,%d)"),width,height);
932 if(m_wxCocoaScrollView)
933 m_wxCocoaScrollView->ClientSizeToSize(width,height);
934 CocoaSetWxWindowSize(width,height);
937 void wxWindow::CocoaSetWxWindowSize(int width, int height)
939 wxWindowCocoa::DoSetSize(wxDefaultCoord,wxDefaultCoord,width,height,wxSIZE_USE_EXISTING);
942 void wxWindow::SetLabel(const wxString& WXUNUSED(label))
944 // Intentional no-op.
947 wxString wxWindow::GetLabel() const
949 // General Get/Set of labels is implemented in wxControlBase
950 wxLogDebug(wxT("wxWindow::GetLabel: Should be overridden if needed."));
951 return wxEmptyString;
954 int wxWindow::GetCharHeight() const
960 int wxWindow::GetCharWidth() const
966 void wxWindow::GetTextExtent(const wxString& string, int *x, int *y,
967 int *descent, int *externalLeading, const wxFont *theFont) const
972 // Coordinates relative to the window
973 void wxWindow::WarpPointer (int x_pos, int y_pos)
978 int wxWindow::GetScrollPos(int orient) const
984 // This now returns the whole range, not just the number
985 // of positions that we can scroll.
986 int wxWindow::GetScrollRange(int orient) const
992 int wxWindow::GetScrollThumb(int orient) const
998 void wxWindow::SetScrollPos(int orient, int pos, bool refresh)
1003 void wxWindow::CocoaCreateNSScrollView()
1005 if(!m_wxCocoaScrollView)
1007 m_wxCocoaScrollView = new wxWindowCocoaScrollView(this);
1011 // New function that will replace some of the above.
1012 void wxWindow::SetScrollbar(int orient, int pos, int thumbVisible,
1013 int range, bool refresh)
1015 CocoaCreateNSScrollView();
1019 // Does a physical scroll
1020 void wxWindow::ScrollWindow(int dx, int dy, const wxRect *rect)
1025 void wxWindow::DoSetVirtualSize( int x, int y )
1027 wxWindowBase::DoSetVirtualSize(x,y);
1028 CocoaCreateNSScrollView();
1029 [m_cocoaNSView setFrameSize:NSMakeSize(m_virtualSize.x,m_virtualSize.y)];
1032 bool wxWindow::SetFont(const wxFont& font)
1034 // FIXME: We may need to handle wx font inheritance.
1035 return wxWindowBase::SetFont(font);
1038 #if 0 // these are used when debugging the algorithm.
1039 static char const * const comparisonresultStrings[] =
1046 class CocoaWindowCompareContext
1048 DECLARE_NO_COPY_CLASS(CocoaWindowCompareContext)
1050 CocoaWindowCompareContext(); // Not implemented
1051 CocoaWindowCompareContext(NSView *target, NSArray *subviews)
1054 // Cocoa sorts subviews in-place.. make a copy
1055 m_subviews = [subviews copy];
1057 ~CocoaWindowCompareContext()
1058 { // release the copy
1059 [m_subviews release];
1062 { return m_target; }
1064 { return m_subviews; }
1065 /* Helper function that returns the comparison based off of the original ordering */
1066 CocoaWindowCompareFunctionResult CompareUsingOriginalOrdering(id first, id second)
1068 NSUInteger firstI = [m_subviews indexOfObjectIdenticalTo:first];
1069 NSUInteger secondI = [m_subviews indexOfObjectIdenticalTo:second];
1070 // NOTE: If either firstI or secondI is NSNotFound then it will be NSIntegerMax and thus will
1071 // likely compare higher than the other view which is reasonable considering the only way that
1072 // can happen is if the subview was added after our call to subviews but before the call to
1073 // sortSubviewsUsingFunction:context:. Thus we don't bother checking. Particularly because
1074 // that case should never occur anyway because that would imply a multi-threaded GUI call
1075 // which is a big no-no with Cocoa.
1077 // Subviews are ordered from back to front meaning one that is already lower will have an lower index.
1078 NSComparisonResult result = (firstI < secondI)
1079 ? NSOrderedAscending /* -1 */
1080 : (firstI > secondI)
1081 ? NSOrderedDescending /* 1 */
1082 : NSOrderedSame /* 0 */;
1084 #if 0 // Enable this if you need to debug the algorithm.
1085 NSLog(@"%@ [%d] %s %@ [%d]\n", first, firstI, comparisonresultStrings[result+1], second, secondI);
1090 /* The subview we are trying to Raise or Lower */
1092 /* A copy of the original array of subviews */
1093 NSArray *m_subviews;
1096 /* Causes Cocoa to raise the target view to the top of the Z-Order by telling the sort function that
1097 * the target view is always higher than every other view. When comparing two views neither of
1098 * which is the target, it returns the correct response based on the original ordering
1100 static CocoaWindowCompareFunctionResult CocoaRaiseWindowCompareFunction(id first, id second, void *ctx)
1102 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
1103 // first should be ordered higher
1104 if(first==compareContext->target())
1105 return NSOrderedDescending;
1106 // second should be ordered higher
1107 if(second==compareContext->target())
1108 return NSOrderedAscending;
1109 return compareContext->CompareUsingOriginalOrdering(first,second);
1112 // Raise the window to the top of the Z order
1113 void wxWindow::Raise()
1115 // wxAutoNSAutoreleasePool pool;
1116 NSView *nsview = GetNSViewForSuperview();
1117 NSView *superview = [nsview superview];
1118 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
1120 [superview sortSubviewsUsingFunction:
1121 CocoaRaiseWindowCompareFunction
1122 context: &compareContext];
1125 /* Causes Cocoa to lower the target view to the bottom of the Z-Order by telling the sort function that
1126 * the target view is always lower than every other view. When comparing two views neither of
1127 * which is the target, it returns the correct response based on the original ordering
1129 static CocoaWindowCompareFunctionResult CocoaLowerWindowCompareFunction(id first, id second, void *ctx)
1131 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
1132 // first should be ordered lower
1133 if(first==compareContext->target())
1134 return NSOrderedAscending;
1135 // second should be ordered lower
1136 if(second==compareContext->target())
1137 return NSOrderedDescending;
1138 return compareContext->CompareUsingOriginalOrdering(first,second);
1141 // Lower the window to the bottom of the Z order
1142 void wxWindow::Lower()
1144 NSView *nsview = GetNSViewForSuperview();
1145 NSView *superview = [nsview superview];
1146 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
1149 NSLog(@"Target:\n%@\n", nsview);
1150 NSLog(@"Before:\n%@\n", compareContext.subviews());
1152 [superview sortSubviewsUsingFunction:
1153 CocoaLowerWindowCompareFunction
1154 context: &compareContext];
1156 NSLog(@"After:\n%@\n", [superview subviews]);
1160 bool wxWindow::DoPopupMenu(wxMenu *menu, int x, int y)
1165 // Get the window with the focus
1166 wxWindow *wxWindowBase::DoFindFocus()
1168 // Basically we are somewhat emulating the responder chain here except
1169 // we are only loking for the first responder in the key window or
1170 // upon failing to find one if the main window is different we look
1171 // for the first responder in the main window.
1173 // Note that the firstResponder doesn't necessarily have to be an
1174 // NSView but wxCocoaNSView::GetFromCocoa() will simply return
1175 // NULL unless it finds its argument in its hash map.
1179 NSWindow *keyWindow = [[NSApplication sharedApplication] keyWindow];
1180 win = wxCocoaNSView::GetFromCocoa(static_cast<NSView*>([keyWindow firstResponder]));
1182 return win->GetWxWindow();
1184 NSWindow *mainWindow = [[NSApplication sharedApplication] keyWindow];
1185 if(mainWindow == keyWindow)
1187 win = wxCocoaNSView::GetFromCocoa(static_cast<NSView*>([mainWindow firstResponder]));
1189 return win->GetWxWindow();
1194 /* static */ wxWindow *wxWindowBase::GetCapture()
1197 return wxWindowCocoa::sm_capturedWindow;
1200 wxWindow *wxGetActiveWindow()
1206 wxPoint wxGetMousePosition()
1209 return wxDefaultPosition;
1212 wxMouseState wxGetMouseState()
1219 wxWindow* wxFindWindowAtPointer(wxPoint& pt)
1221 pt = wxGetMousePosition();
1226 // ========================================================================
1227 // wxCocoaTrackingRectManager
1228 // ========================================================================
1230 wxCocoaTrackingRectManager::wxCocoaTrackingRectManager(wxWindow *window)
1233 m_isTrackingRectActive = false;
1234 m_runLoopObserver = NULL;
1235 BuildTrackingRect();
1238 void wxCocoaTrackingRectManager::ClearTrackingRect()
1240 if(m_isTrackingRectActive)
1242 [m_window->GetNSView() removeTrackingRect:m_trackingRectTag];
1243 m_isTrackingRectActive = false;
1245 // If we were doing periodic events we need to clear those too
1246 StopSynthesizingEvents();
1249 void wxCocoaTrackingRectManager::StopSynthesizingEvents()
1251 if(m_runLoopObserver != NULL)
1253 CFRunLoopRemoveObserver([[NSRunLoop currentRunLoop] getCFRunLoop], m_runLoopObserver, kCFRunLoopCommonModes);
1254 CFRelease(m_runLoopObserver);
1255 m_runLoopObserver = NULL;
1259 void wxCocoaTrackingRectManager::BuildTrackingRect()
1261 // Pool here due to lack of one during wx init phase
1262 wxAutoNSAutoreleasePool pool;
1264 wxASSERT_MSG(!m_isTrackingRectActive, wxT("Tracking rect was not cleared"));
1265 if([m_window->GetNSView() window] != nil)
1267 m_trackingRectTag = [m_window->GetNSView() addTrackingRect:[m_window->GetNSView() visibleRect] owner:m_window->GetNSView() userData:NULL assumeInside:NO];
1268 m_isTrackingRectActive = true;
1272 static NSPoint s_lastScreenMouseLocation = NSZeroPoint;
1274 static void SynthesizeMouseMovedEvent(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info)
1276 NSPoint screenMouseLocation = [NSEvent mouseLocation];
1277 if(screenMouseLocation.x != s_lastScreenMouseLocation.x || screenMouseLocation.y != s_lastScreenMouseLocation.y)
1279 wxCocoaNSView *win = reinterpret_cast<wxCocoaNSView*>(info);
1280 win->Cocoa_synthesizeMouseMoved();
1284 void wxCocoaTrackingRectManager::BeginSynthesizingEvents()
1286 CFRunLoopObserverContext observerContext =
1288 , static_cast<wxCocoaNSView*>(m_window)
1293 m_runLoopObserver = CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopBeforeWaiting, TRUE, 0, SynthesizeMouseMovedEvent, &observerContext);
1294 CFRunLoopAddObserver([[NSRunLoop currentRunLoop] getCFRunLoop], m_runLoopObserver, kCFRunLoopCommonModes);
1297 void wxCocoaTrackingRectManager::RebuildTrackingRect()
1299 ClearTrackingRect();
1300 BuildTrackingRect();
1303 wxCocoaTrackingRectManager::~wxCocoaTrackingRectManager()
1305 ClearTrackingRect();
1308 bool wxCocoaTrackingRectManager::IsOwnerOfEvent(NSEvent *anEvent)
1310 return m_isTrackingRectActive && (m_trackingRectTag == [anEvent trackingNumber]);