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/NSArray.h>
28 #import <Foundation/NSRunLoop.h>
29 #include "wx/cocoa/objc/NSView.h"
30 #import <AppKit/NSEvent.h>
31 #import <AppKit/NSScrollView.h>
32 #import <AppKit/NSColor.h>
33 #import <AppKit/NSClipView.h>
34 #import <Foundation/NSException.h>
35 #import <AppKit/NSApplication.h>
36 #import <AppKit/NSWindow.h>
38 // Turn this on to paint green over the dummy views for debugging
39 #undef WXCOCOA_FILL_DUMMY_VIEW
41 #ifdef WXCOCOA_FILL_DUMMY_VIEW
42 #import <AppKit/NSBezierPath.h>
43 #endif //def WXCOCOA_FILL_DUMMY_VIEW
45 /* NSComparisonResult is typedef'd as an enum pre-Leopard but typedef'd as
46 * NSInteger post-Leopard. Pre-Leopard the Cocoa toolkit expects a function
47 * returning int and not NSComparisonResult. Post-Leopard the Cocoa toolkit
48 * expects a function returning the new non-enum NSComparsionResult.
49 * Hence we create a typedef named CocoaWindowCompareFunctionResult.
51 #if defined(NSINTEGER_DEFINED)
52 typedef NSComparisonResult CocoaWindowCompareFunctionResult;
54 typedef int CocoaWindowCompareFunctionResult;
57 // A category for methods that are only present in Panther's SDK
58 @interface NSView(wxNSViewPrePantherCompatibility)
59 - (void)getRectsBeingDrawn:(const NSRect **)rects count:(int *)count;
62 NSPoint CocoaTransformNSViewBoundsToWx(NSView *nsview, NSPoint pointBounds)
64 wxCHECK_MSG(nsview, pointBounds, wxT("Need to have a Cocoa view to do translation"));
65 if([nsview isFlipped])
67 NSRect ourBounds = [nsview bounds];
70 , ourBounds.size.height - pointBounds.y
74 NSRect CocoaTransformNSViewBoundsToWx(NSView *nsview, NSRect rectBounds)
76 wxCHECK_MSG(nsview, rectBounds, wxT("Need to have a Cocoa view to do translation"));
77 if([nsview isFlipped])
79 NSRect ourBounds = [nsview bounds];
82 , ourBounds.size.height - (rectBounds.origin.y + rectBounds.size.height)
83 , rectBounds.size.width
84 , rectBounds.size.height
88 NSPoint CocoaTransformNSViewWxToBounds(NSView *nsview, NSPoint pointWx)
90 wxCHECK_MSG(nsview, pointWx, wxT("Need to have a Cocoa view to do translation"));
91 if([nsview isFlipped])
93 NSRect ourBounds = [nsview bounds];
96 , ourBounds.size.height - pointWx.y
100 NSRect CocoaTransformNSViewWxToBounds(NSView *nsview, NSRect rectWx)
102 wxCHECK_MSG(nsview, rectWx, wxT("Need to have a Cocoa view to do translation"));
103 if([nsview isFlipped])
105 NSRect ourBounds = [nsview bounds];
108 , ourBounds.size.height - (rectWx.origin.y + rectWx.size.height)
114 // ========================================================================
115 // wxWindowCocoaHider
116 // ========================================================================
117 class wxWindowCocoaHider: protected wxCocoaNSView
119 DECLARE_NO_COPY_CLASS(wxWindowCocoaHider)
121 wxWindowCocoaHider(wxWindow *owner);
122 virtual ~wxWindowCocoaHider();
123 inline WX_NSView GetNSView() { return m_dummyNSView; }
125 wxWindowCocoa *m_owner;
126 WX_NSView m_dummyNSView;
127 virtual void Cocoa_FrameChanged(void);
128 virtual void Cocoa_synthesizeMouseMoved(void) {}
129 #ifdef WXCOCOA_FILL_DUMMY_VIEW
130 virtual bool Cocoa_drawRect(const NSRect& rect);
131 #endif //def WXCOCOA_FILL_DUMMY_VIEW
133 wxWindowCocoaHider();
136 // ========================================================================
137 // wxWindowCocoaScrollView
138 // ========================================================================
139 class wxWindowCocoaScrollView: protected wxCocoaNSView
141 DECLARE_NO_COPY_CLASS(wxWindowCocoaScrollView)
143 wxWindowCocoaScrollView(wxWindow *owner);
144 virtual ~wxWindowCocoaScrollView();
145 inline WX_NSScrollView GetNSScrollView() { return m_cocoaNSScrollView; }
146 void ClientSizeToSize(int &width, int &height);
147 void DoGetClientSize(int *x, int *y) const;
149 void Unencapsulate();
151 wxWindowCocoa *m_owner;
152 WX_NSScrollView m_cocoaNSScrollView;
153 virtual void Cocoa_FrameChanged(void);
154 virtual void Cocoa_synthesizeMouseMoved(void) {}
156 wxWindowCocoaScrollView();
159 // ========================================================================
161 // ========================================================================
162 @interface wxDummyNSView : NSView
163 - (NSView *)hitTest:(NSPoint)aPoint;
165 WX_DECLARE_GET_OBJC_CLASS(wxDummyNSView,NSView)
167 @implementation wxDummyNSView : NSView
168 - (NSView *)hitTest:(NSPoint)aPoint
174 WX_IMPLEMENT_GET_OBJC_CLASS(wxDummyNSView,NSView)
176 // ========================================================================
177 // wxWindowCocoaHider
178 // ========================================================================
179 wxWindowCocoaHider::wxWindowCocoaHider(wxWindow *owner)
183 wxASSERT(owner->GetNSViewForHiding());
184 m_dummyNSView = [[WX_GET_OBJC_CLASS(wxDummyNSView) alloc]
185 initWithFrame:[owner->GetNSViewForHiding() frame]];
186 [m_dummyNSView setAutoresizingMask: [owner->GetNSViewForHiding() autoresizingMask]];
187 AssociateNSView(m_dummyNSView);
190 wxWindowCocoaHider::~wxWindowCocoaHider()
192 DisassociateNSView(m_dummyNSView);
193 [m_dummyNSView release];
196 void wxWindowCocoaHider::Cocoa_FrameChanged(void)
198 // Keep the real window in synch with the dummy
199 wxASSERT(m_dummyNSView);
200 [m_owner->GetNSViewForHiding() setFrame:[m_dummyNSView frame]];
204 #ifdef WXCOCOA_FILL_DUMMY_VIEW
205 bool wxWindowCocoaHider::Cocoa_drawRect(const NSRect& rect)
207 NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:rect];
208 [[NSColor greenColor] set];
213 #endif //def WXCOCOA_FILL_DUMMY_VIEW
215 // ========================================================================
216 // wxFlippedNSClipView
217 // ========================================================================
218 @interface wxFlippedNSClipView : NSClipView
221 WX_DECLARE_GET_OBJC_CLASS(wxFlippedNSClipView,NSClipView)
223 @implementation wxFlippedNSClipView : NSClipView
230 WX_IMPLEMENT_GET_OBJC_CLASS(wxFlippedNSClipView,NSClipView)
232 // ========================================================================
233 // wxWindowCocoaScrollView
234 // ========================================================================
235 wxWindowCocoaScrollView::wxWindowCocoaScrollView(wxWindow *owner)
238 wxAutoNSAutoreleasePool pool;
240 wxASSERT(owner->GetNSView());
241 m_cocoaNSScrollView = [[NSScrollView alloc]
242 initWithFrame:[owner->GetNSView() frame]];
243 AssociateNSView(m_cocoaNSScrollView);
245 /* Replace the default NSClipView with a flipped one. This ensures
246 scrolling is "pinned" to the top-left instead of bottom-right. */
247 NSClipView *flippedClip = [[WX_GET_OBJC_CLASS(wxFlippedNSClipView) alloc]
248 initWithFrame: [[m_cocoaNSScrollView contentView] frame]];
249 [m_cocoaNSScrollView setContentView:flippedClip];
250 [flippedClip release];
252 [m_cocoaNSScrollView setBackgroundColor: [NSColor windowBackgroundColor]];
253 [m_cocoaNSScrollView setHasHorizontalScroller: YES];
254 [m_cocoaNSScrollView setHasVerticalScroller: YES];
258 void wxWindowCocoaScrollView::Encapsulate()
260 // Set the scroll view autoresizingMask to match the current NSView
261 [m_cocoaNSScrollView setAutoresizingMask: [m_owner->GetNSView() autoresizingMask]];
262 [m_owner->GetNSView() setAutoresizingMask: NSViewNotSizable];
263 // NOTE: replaceSubView will cause m_cocaNSView to be released
264 // except when it hasn't been added into an NSView hierarchy in which
265 // case it doesn't need to be and this should work out to a no-op
266 m_owner->CocoaReplaceView(m_owner->GetNSView(), m_cocoaNSScrollView);
267 // The NSView is still retained by owner
268 [m_cocoaNSScrollView setDocumentView: m_owner->GetNSView()];
269 // Now it's also retained by the NSScrollView
272 void wxWindowCocoaScrollView::Unencapsulate()
274 [m_cocoaNSScrollView setDocumentView: nil];
275 m_owner->CocoaReplaceView(m_cocoaNSScrollView, m_owner->GetNSView());
276 if(![[m_owner->GetNSView() superview] isFlipped])
277 [m_owner->GetNSView() setAutoresizingMask: NSViewMinYMargin];
280 wxWindowCocoaScrollView::~wxWindowCocoaScrollView()
282 DisassociateNSView(m_cocoaNSScrollView);
283 [m_cocoaNSScrollView release];
286 void wxWindowCocoaScrollView::ClientSizeToSize(int &width, int &height)
288 NSSize frameSize = [NSScrollView
289 frameSizeForContentSize: NSMakeSize(width,height)
290 hasHorizontalScroller: [m_cocoaNSScrollView hasHorizontalScroller]
291 hasVerticalScroller: [m_cocoaNSScrollView hasVerticalScroller]
292 borderType: [m_cocoaNSScrollView borderType]];
293 width = (int)frameSize.width;
294 height = (int)frameSize.height;
297 void wxWindowCocoaScrollView::DoGetClientSize(int *x, int *y) const
299 NSSize nssize = [m_cocoaNSScrollView contentSize];
301 *x = (int)nssize.width;
303 *y = (int)nssize.height;
306 void wxWindowCocoaScrollView::Cocoa_FrameChanged(void)
308 wxLogTrace(wxTRACE_COCOA,wxT("Cocoa_FrameChanged"));
309 wxSizeEvent event(m_owner->GetSize(), m_owner->GetId());
310 event.SetEventObject(m_owner);
311 m_owner->GetEventHandler()->ProcessEvent(event);
314 // ========================================================================
316 // ========================================================================
317 // normally the base classes aren't included, but wxWindow is special
318 #ifdef __WXUNIVERSAL__
319 IMPLEMENT_ABSTRACT_CLASS(wxWindowCocoa, wxWindowBase)
321 IMPLEMENT_DYNAMIC_CLASS(wxWindow, wxWindowBase)
324 BEGIN_EVENT_TABLE(wxWindowCocoa, wxWindowBase)
327 wxWindow *wxWindowCocoa::sm_capturedWindow = NULL;
330 void wxWindowCocoa::Init()
332 m_cocoaNSView = NULL;
334 m_wxCocoaScrollView = NULL;
335 m_isBeingDeleted = false;
337 m_visibleTrackingRectManager = NULL;
341 bool wxWindow::Create(wxWindow *parent, wxWindowID winid,
345 const wxString& name)
347 if(!CreateBase(parent,winid,pos,size,style,wxDefaultValidator,name))
350 // TODO: create the window
351 m_cocoaNSView = NULL;
352 SetNSView([[WX_GET_OBJC_CLASS(WXNSView) alloc] initWithFrame: MakeDefaultNSRect(size)]);
353 [m_cocoaNSView release];
357 m_parent->AddChild(this);
358 m_parent->CocoaAddChild(this);
359 SetInitialFrameRect(pos,size);
366 wxWindow::~wxWindow()
368 wxAutoNSAutoreleasePool pool;
371 // Make sure our parent (in the wxWidgets sense) is our superview
372 // before we go removing from it.
373 if(m_parent && m_parent->GetNSView()==[GetNSViewForSuperview() superview])
374 CocoaRemoveFromParent();
376 delete m_wxCocoaScrollView;
382 void wxWindowCocoa::CocoaAddChild(wxWindowCocoa *child)
384 // Pool here due to lack of one during wx init phase
385 wxAutoNSAutoreleasePool pool;
387 NSView *childView = child->GetNSViewForSuperview();
390 [m_cocoaNSView addSubview: childView];
391 child->m_isShown = !m_cocoaHider;
394 void wxWindowCocoa::CocoaRemoveFromParent(void)
396 [GetNSViewForSuperview() removeFromSuperview];
399 void wxWindowCocoa::SetNSView(WX_NSView cocoaNSView)
401 // Clear the visible area tracking rect if we have one.
402 delete m_visibleTrackingRectManager;
403 m_visibleTrackingRectManager = NULL;
405 bool need_debug = cocoaNSView || m_cocoaNSView;
406 if(need_debug) wxLogTrace(wxTRACE_COCOA_RetainRelease,wxT("wxWindowCocoa=%p::SetNSView [m_cocoaNSView=%p retainCount]=%d"),this,m_cocoaNSView,[m_cocoaNSView retainCount]);
407 DisassociateNSView(m_cocoaNSView);
408 [cocoaNSView retain];
409 [m_cocoaNSView release];
410 m_cocoaNSView = cocoaNSView;
411 AssociateNSView(m_cocoaNSView);
412 if(need_debug) wxLogTrace(wxTRACE_COCOA_RetainRelease,wxT("wxWindowCocoa=%p::SetNSView [cocoaNSView=%p retainCount]=%d"),this,cocoaNSView,[cocoaNSView retainCount]);
415 WX_NSView wxWindowCocoa::GetNSViewForSuperview() const
418 ? m_cocoaHider->GetNSView()
419 : m_wxCocoaScrollView
420 ? m_wxCocoaScrollView->GetNSScrollView()
424 WX_NSView wxWindowCocoa::GetNSViewForHiding() const
426 return m_wxCocoaScrollView
427 ? m_wxCocoaScrollView->GetNSScrollView()
431 NSPoint wxWindowCocoa::CocoaTransformBoundsToWx(NSPoint pointBounds)
433 // TODO: Handle scrolling offset
434 return CocoaTransformNSViewBoundsToWx(GetNSView(), pointBounds);
437 NSRect wxWindowCocoa::CocoaTransformBoundsToWx(NSRect rectBounds)
439 // TODO: Handle scrolling offset
440 return CocoaTransformNSViewBoundsToWx(GetNSView(), rectBounds);
443 NSPoint wxWindowCocoa::CocoaTransformWxToBounds(NSPoint pointWx)
445 // TODO: Handle scrolling offset
446 return CocoaTransformNSViewWxToBounds(GetNSView(), pointWx);
449 NSRect wxWindowCocoa::CocoaTransformWxToBounds(NSRect rectWx)
451 // TODO: Handle scrolling offset
452 return CocoaTransformNSViewWxToBounds(GetNSView(), rectWx);
455 WX_NSAffineTransform wxWindowCocoa::CocoaGetWxToBoundsTransform()
457 // TODO: Handle scrolling offset
458 NSAffineTransform *transform = wxDC::CocoaGetWxToBoundsTransform([GetNSView() isFlipped], [GetNSView() bounds].size.height);
462 bool wxWindowCocoa::Cocoa_drawRect(const NSRect &rect)
464 wxLogTrace(wxTRACE_COCOA,wxT("Cocoa_drawRect"));
465 // Recursion can happen if the event loop runs from within the paint
466 // handler. For instance, if an assertion dialog is shown.
467 // FIXME: This seems less than ideal.
470 wxLogDebug(wxT("Paint event recursion!"));
475 // Set m_updateRegion
476 const NSRect *rects = ▭ // The bounding box of the region
477 NSInteger countRects = 1;
478 // Try replacing the larger rectangle with a list of smaller ones:
479 if ([GetNSView() respondsToSelector:@selector(getRectsBeingDrawn:count:)])
480 [GetNSView() getRectsBeingDrawn:&rects count:&countRects];
482 NSRect *transformedRects = (NSRect*)malloc(sizeof(NSRect)*countRects);
483 for(int i=0; i<countRects; i++)
485 transformedRects[i] = CocoaTransformBoundsToWx(rects[i]);
487 m_updateRegion = wxRegion(transformedRects,countRects);
488 free(transformedRects);
490 wxPaintEvent event(m_windowId);
491 event.SetEventObject(this);
492 bool ret = GetEventHandler()->ProcessEvent(event);
497 void wxWindowCocoa::InitMouseEvent(wxMouseEvent& event, WX_NSEvent cocoaEvent)
499 wxASSERT_MSG([m_cocoaNSView window]==[cocoaEvent window],wxT("Mouse event for different NSWindow"));
500 // Mouse events happen at the NSWindow level so we need to convert
501 // into our bounds coordinates then convert to wx coordinates.
502 NSPoint cocoaPoint = [m_cocoaNSView convertPoint:[(NSEvent*)cocoaEvent locationInWindow] fromView:nil];
503 NSPoint pointWx = CocoaTransformBoundsToWx(cocoaPoint);
504 // FIXME: Should we be adjusting for client area origin?
505 const wxPoint &clientorigin = GetClientAreaOrigin();
506 event.m_x = (wxCoord)pointWx.x - clientorigin.x;
507 event.m_y = (wxCoord)pointWx.y - clientorigin.y;
509 event.m_shiftDown = [cocoaEvent modifierFlags] & NSShiftKeyMask;
510 event.m_controlDown = [cocoaEvent modifierFlags] & NSControlKeyMask;
511 event.m_altDown = [cocoaEvent modifierFlags] & NSAlternateKeyMask;
512 event.m_metaDown = [cocoaEvent modifierFlags] & NSCommandKeyMask;
514 // TODO: set timestamp?
515 event.SetEventObject(this);
516 event.SetId(GetId());
519 bool wxWindowCocoa::Cocoa_mouseMoved(WX_NSEvent theEvent)
521 wxMouseEvent event(wxEVT_MOTION);
522 InitMouseEvent(event,theEvent);
523 wxLogTrace(wxTRACE_COCOA,wxT("wxWindow=%p::Cocoa_mouseMoved @%d,%d"),this,event.m_x,event.m_y);
524 return GetEventHandler()->ProcessEvent(event);
527 void wxWindowCocoa::Cocoa_synthesizeMouseMoved()
529 wxMouseEvent event(wxEVT_MOTION);
530 NSWindow *window = [GetNSView() window];
531 NSPoint locationInWindow = [window mouseLocationOutsideOfEventStream];
532 NSPoint cocoaPoint = [m_cocoaNSView convertPoint:locationInWindow fromView:nil];
534 NSPoint pointWx = CocoaTransformBoundsToWx(cocoaPoint);
535 // FIXME: Should we be adjusting for client area origin?
536 const wxPoint &clientorigin = GetClientAreaOrigin();
537 event.m_x = (wxCoord)pointWx.x - clientorigin.x;
538 event.m_y = (wxCoord)pointWx.y - clientorigin.y;
540 // TODO: Handle shift, control, alt, meta flags
541 event.SetEventObject(this);
542 event.SetId(GetId());
544 wxLogTrace(wxTRACE_COCOA,wxT("wxwin=%p Synthesized Mouse Moved @%d,%d"),this,event.m_x,event.m_y);
545 GetEventHandler()->ProcessEvent(event);
548 bool wxWindowCocoa::Cocoa_mouseEntered(WX_NSEvent theEvent)
550 if(m_visibleTrackingRectManager != NULL && m_visibleTrackingRectManager->IsOwnerOfEvent(theEvent))
552 m_visibleTrackingRectManager->BeginSynthesizingEvents();
554 // Although we synthesize the mouse moved events we don't poll for them but rather send them only when
555 // some other event comes in. That other event is (guess what) mouse moved events that will be sent
556 // to the NSWindow which will forward them on to the first responder. We are not likely to be the
557 // first responder, so the mouseMoved: events are effectively discarded.
558 [[GetNSView() window] setAcceptsMouseMovedEvents:YES];
560 wxMouseEvent event(wxEVT_ENTER_WINDOW);
561 InitMouseEvent(event,theEvent);
562 wxLogTrace(wxTRACE_COCOA,wxT("wxwin=%p Mouse Entered @%d,%d"),this,event.m_x,event.m_y);
563 return GetEventHandler()->ProcessEvent(event);
569 bool wxWindowCocoa::Cocoa_mouseExited(WX_NSEvent theEvent)
571 if(m_visibleTrackingRectManager != NULL && m_visibleTrackingRectManager->IsOwnerOfEvent(theEvent))
573 m_visibleTrackingRectManager->StopSynthesizingEvents();
575 wxMouseEvent event(wxEVT_LEAVE_WINDOW);
576 InitMouseEvent(event,theEvent);
577 wxLogTrace(wxTRACE_COCOA,wxT("wxwin=%p Mouse Exited @%d,%d"),this,event.m_x,event.m_y);
578 return GetEventHandler()->ProcessEvent(event);
584 bool wxWindowCocoa::Cocoa_mouseDown(WX_NSEvent theEvent)
586 wxMouseEvent event([theEvent clickCount]<2?wxEVT_LEFT_DOWN:wxEVT_LEFT_DCLICK);
587 InitMouseEvent(event,theEvent);
588 wxLogTrace(wxTRACE_COCOA,wxT("Mouse Down @%d,%d num clicks=%d"),event.m_x,event.m_y,[theEvent clickCount]);
589 return GetEventHandler()->ProcessEvent(event);
592 bool wxWindowCocoa::Cocoa_mouseDragged(WX_NSEvent theEvent)
594 wxMouseEvent event(wxEVT_MOTION);
595 InitMouseEvent(event,theEvent);
596 event.m_leftDown = true;
597 wxLogTrace(wxTRACE_COCOA,wxT("Mouse Drag @%d,%d"),event.m_x,event.m_y);
598 return GetEventHandler()->ProcessEvent(event);
601 bool wxWindowCocoa::Cocoa_mouseUp(WX_NSEvent theEvent)
603 wxMouseEvent event(wxEVT_LEFT_UP);
604 InitMouseEvent(event,theEvent);
605 wxLogTrace(wxTRACE_COCOA,wxT("Mouse Up @%d,%d"),event.m_x,event.m_y);
606 return GetEventHandler()->ProcessEvent(event);
609 bool wxWindowCocoa::Cocoa_rightMouseDown(WX_NSEvent theEvent)
611 wxMouseEvent event([theEvent clickCount]<2?wxEVT_RIGHT_DOWN:wxEVT_RIGHT_DCLICK);
612 InitMouseEvent(event,theEvent);
613 wxLogDebug(wxT("Mouse Down @%d,%d num clicks=%d"),event.m_x,event.m_y,[theEvent clickCount]);
614 return GetEventHandler()->ProcessEvent(event);
617 bool wxWindowCocoa::Cocoa_rightMouseDragged(WX_NSEvent theEvent)
619 wxMouseEvent event(wxEVT_MOTION);
620 InitMouseEvent(event,theEvent);
621 event.m_rightDown = true;
622 wxLogDebug(wxT("Mouse Drag @%d,%d"),event.m_x,event.m_y);
623 return GetEventHandler()->ProcessEvent(event);
626 bool wxWindowCocoa::Cocoa_rightMouseUp(WX_NSEvent theEvent)
628 wxMouseEvent event(wxEVT_RIGHT_UP);
629 InitMouseEvent(event,theEvent);
630 wxLogDebug(wxT("Mouse Up @%d,%d"),event.m_x,event.m_y);
631 return GetEventHandler()->ProcessEvent(event);
634 bool wxWindowCocoa::Cocoa_otherMouseDown(WX_NSEvent theEvent)
639 bool wxWindowCocoa::Cocoa_otherMouseDragged(WX_NSEvent theEvent)
644 bool wxWindowCocoa::Cocoa_otherMouseUp(WX_NSEvent theEvent)
649 void wxWindowCocoa::Cocoa_FrameChanged(void)
651 wxLogTrace(wxTRACE_COCOA,wxT("wxWindow=%p::Cocoa_FrameChanged"),this);
652 if(m_visibleTrackingRectManager != NULL)
653 m_visibleTrackingRectManager->RebuildTrackingRect();
654 wxSizeEvent event(GetSize(), m_windowId);
655 event.SetEventObject(this);
656 GetEventHandler()->ProcessEvent(event);
659 bool wxWindowCocoa::Cocoa_resetCursorRects()
661 wxLogTrace(wxTRACE_COCOA,wxT("wxWindow=%p::Cocoa_resetCursorRects"),this);
662 if(m_visibleTrackingRectManager != NULL)
663 m_visibleTrackingRectManager->RebuildTrackingRect();
665 if(!m_cursor.GetNSCursor())
668 [GetNSView() addCursorRect: [GetNSView() visibleRect] cursor: m_cursor.GetNSCursor()];
673 bool wxWindowCocoa::SetCursor(const wxCursor &cursor)
675 if(!wxWindowBase::SetCursor(cursor))
677 // Invalidate the cursor rects so the cursor will change
678 [[GetNSView() window] invalidateCursorRectsForView:GetNSView()];
682 bool wxWindowCocoa::Cocoa_viewDidMoveToWindow()
684 wxLogTrace(wxTRACE_COCOA,wxT("wxWindow=%p::viewDidMoveToWindow"),this);
685 // Set up new tracking rects. I am reasonably sure the new window must be set before doing this.
686 if(m_visibleTrackingRectManager != NULL)
687 m_visibleTrackingRectManager->BuildTrackingRect();
691 bool wxWindowCocoa::Cocoa_viewWillMoveToWindow(WX_NSWindow newWindow)
693 wxLogTrace(wxTRACE_COCOA,wxT("wxWindow=%p::viewWillMoveToWindow:%p"),this, newWindow);
694 // Clear tracking rects. It is imperative this be done before the new window is set.
695 if(m_visibleTrackingRectManager != NULL)
696 m_visibleTrackingRectManager->ClearTrackingRect();
700 bool wxWindow::Close(bool force)
702 // The only reason this function exists is that it is virtual and
703 // wxTopLevelWindowCocoa will override it.
704 return wxWindowBase::Close(force);
707 void wxWindow::CocoaReplaceView(WX_NSView oldView, WX_NSView newView)
709 [[oldView superview] replaceSubview:oldView with:newView];
712 void wxWindow::DoEnable(bool enable)
714 CocoaSetEnabled(enable);
717 bool wxWindow::Show(bool show)
719 wxAutoNSAutoreleasePool pool;
720 // If the window is marked as visible, then it shouldn't have a dummy view
721 // If the window is marked hidden, then it should have a dummy view
722 // wxSpinCtrl (generic) abuses m_isShown, don't use it for any logic
723 // wxASSERT_MSG( (m_isShown && !m_dummyNSView) || (!m_isShown && m_dummyNSView),wxT("wxWindow: m_isShown does not agree with m_dummyNSView"));
724 // Return false if there isn't a window to show or hide
725 NSView *cocoaView = GetNSViewForHiding();
730 // If state isn't changing, return false
733 CocoaReplaceView(m_cocoaHider->GetNSView(), cocoaView);
734 wxASSERT(![m_cocoaHider->GetNSView() superview]);
737 wxASSERT([cocoaView superview]);
741 // If state isn't changing, return false
744 m_cocoaHider = new wxWindowCocoaHider(this);
745 // NOTE: replaceSubview:with will cause m_cocaNSView to be
746 // (auto)released which balances out addSubview
747 CocoaReplaceView(cocoaView, m_cocoaHider->GetNSView());
748 // m_coocaNSView is now only retained by us
749 wxASSERT([m_cocoaHider->GetNSView() superview]);
750 wxASSERT(![cocoaView superview]);
756 void wxWindowCocoa::DoSetSize(int x, int y, int width, int height, int sizeFlags)
758 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":".");
759 int currentX, currentY;
760 int currentW, currentH;
761 DoGetPosition(¤tX, ¤tY);
762 DoGetSize(¤tW, ¤tH);
763 if((x==-1) && !(sizeFlags&wxSIZE_ALLOW_MINUS_ONE))
765 if((y==-1) && !(sizeFlags&wxSIZE_ALLOW_MINUS_ONE))
768 AdjustForParentClientOrigin(x,y,sizeFlags);
770 wxSize size(wxDefaultSize);
772 if((width==-1)&&!(sizeFlags&wxSIZE_ALLOW_MINUS_ONE))
774 if(sizeFlags&wxSIZE_AUTO_WIDTH)
776 size=DoGetBestSize();
782 if((height==-1)&&!(sizeFlags&wxSIZE_ALLOW_MINUS_ONE))
784 if(sizeFlags&wxSIZE_AUTO_HEIGHT)
787 size=DoGetBestSize();
793 DoMoveWindow(x,y,width,height);
798 void wxWindowCocoa::DoSetToolTip( wxToolTip *tip )
800 wxWindowBase::DoSetToolTip(tip);
804 m_tooltip->SetWindow((wxWindow *)this);
810 void wxWindowCocoa::DoMoveWindow(int x, int y, int width, int height)
812 wxAutoNSAutoreleasePool pool;
813 wxLogTrace(wxTRACE_COCOA_Window_Size,wxT("wxWindow=%p::DoMoveWindow(%d,%d,%d,%d)"),this,x,y,width,height);
815 NSView *nsview = GetNSViewForSuperview();
816 NSView *superview = [nsview superview];
818 wxCHECK_RET(GetParent(), wxT("Window can only be placed correctly when it has a parent"));
820 NSRect oldFrameRect = [nsview frame];
821 NSRect newFrameRect = GetParent()->CocoaTransformWxToBounds(NSMakeRect(x,y,width,height));
822 [nsview setFrame:newFrameRect];
823 // Be sure to redraw the parent to reflect the changed position
824 [superview setNeedsDisplayInRect:oldFrameRect];
825 [superview setNeedsDisplayInRect:newFrameRect];
828 void wxWindowCocoa::SetInitialFrameRect(const wxPoint& pos, const wxSize& size)
830 NSView *nsview = GetNSViewForSuperview();
831 NSView *superview = [nsview superview];
832 wxCHECK_RET(superview,wxT("NSView does not have a superview"));
833 wxCHECK_RET(GetParent(), wxT("Window can only be placed correctly when it has a parent"));
834 NSRect frameRect = [nsview frame];
836 frameRect.size.width = size.x;
838 frameRect.size.height = size.y;
839 frameRect.origin.x = pos.x;
840 frameRect.origin.y = pos.y;
841 // Tell Cocoa to change the margin between the bottom of the superview
842 // and the bottom of the control. Keeps the control pinned to the top
843 // of its superview so that its position in the wxWidgets coordinate
844 // system doesn't change.
845 if(![superview isFlipped])
846 [nsview setAutoresizingMask: NSViewMinYMargin];
847 // MUST set the mask before setFrame: which can generate a size event
848 // and cause a scroller to be added!
849 frameRect = GetParent()->CocoaTransformWxToBounds(frameRect);
850 [nsview setFrame: frameRect];
854 void wxWindow::DoGetSize(int *w, int *h) const
856 NSRect cocoaRect = [GetNSViewForSuperview() frame];
858 *w=(int)cocoaRect.size.width;
860 *h=(int)cocoaRect.size.height;
861 wxLogTrace(wxTRACE_COCOA_Window_Size,wxT("wxWindow=%p::DoGetSize = (%d,%d)"),this,(int)cocoaRect.size.width,(int)cocoaRect.size.height);
864 void wxWindow::DoGetPosition(int *x, int *y) const
866 NSView *nsview = GetNSViewForSuperview();
868 NSRect cocoaRect = [nsview frame];
869 NSRect rectWx = GetParent()->CocoaTransformBoundsToWx(cocoaRect);
871 *x=(int)rectWx.origin.x;
873 *y=(int)rectWx.origin.y;
874 wxLogTrace(wxTRACE_COCOA_Window_Size,wxT("wxWindow=%p::DoGetPosition = (%d,%d)"),this,(int)cocoaRect.origin.x,(int)cocoaRect.origin.y);
877 WXWidget wxWindow::GetHandle() const
879 return m_cocoaNSView;
882 wxWindow* wxWindow::GetWxWindow() const
884 return (wxWindow*) this;
887 void wxWindow::Refresh(bool eraseBack, const wxRect *rect)
889 [m_cocoaNSView setNeedsDisplay:YES];
892 void wxWindow::SetFocus()
894 if([GetNSView() acceptsFirstResponder])
895 [[GetNSView() window] makeFirstResponder: GetNSView()];
898 void wxWindow::DoCaptureMouse()
901 sm_capturedWindow = this;
904 void wxWindow::DoReleaseMouse()
907 sm_capturedWindow = NULL;
910 void wxWindow::DoScreenToClient(int *x, int *y) const
915 void wxWindow::DoClientToScreen(int *x, int *y) const
920 // Get size *available for subwindows* i.e. excluding menu bar etc.
921 void wxWindow::DoGetClientSize(int *x, int *y) const
923 wxLogTrace(wxTRACE_COCOA,wxT("DoGetClientSize:"));
924 if(m_wxCocoaScrollView)
925 m_wxCocoaScrollView->DoGetClientSize(x,y);
927 wxWindowCocoa::DoGetSize(x,y);
930 void wxWindow::DoSetClientSize(int width, int height)
932 wxLogTrace(wxTRACE_COCOA_Window_Size,wxT("DoSetClientSize=(%d,%d)"),width,height);
933 if(m_wxCocoaScrollView)
934 m_wxCocoaScrollView->ClientSizeToSize(width,height);
935 CocoaSetWxWindowSize(width,height);
938 void wxWindow::CocoaSetWxWindowSize(int width, int height)
940 wxWindowCocoa::DoSetSize(wxDefaultCoord,wxDefaultCoord,width,height,wxSIZE_USE_EXISTING);
943 void wxWindow::SetLabel(const wxString& WXUNUSED(label))
945 // Intentional no-op.
948 wxString wxWindow::GetLabel() const
950 // General Get/Set of labels is implemented in wxControlBase
951 wxLogDebug(wxT("wxWindow::GetLabel: Should be overridden if needed."));
952 return wxEmptyString;
955 int wxWindow::GetCharHeight() const
961 int wxWindow::GetCharWidth() const
967 void wxWindow::GetTextExtent(const wxString& string, int *x, int *y,
968 int *descent, int *externalLeading, const wxFont *theFont) const
973 // Coordinates relative to the window
974 void wxWindow::WarpPointer (int x_pos, int y_pos)
979 int wxWindow::GetScrollPos(int orient) const
985 // This now returns the whole range, not just the number
986 // of positions that we can scroll.
987 int wxWindow::GetScrollRange(int orient) const
993 int wxWindow::GetScrollThumb(int orient) const
999 void wxWindow::SetScrollPos(int orient, int pos, bool refresh)
1004 void wxWindow::CocoaCreateNSScrollView()
1006 if(!m_wxCocoaScrollView)
1008 m_wxCocoaScrollView = new wxWindowCocoaScrollView(this);
1012 // New function that will replace some of the above.
1013 void wxWindow::SetScrollbar(int orient, int pos, int thumbVisible,
1014 int range, bool refresh)
1016 CocoaCreateNSScrollView();
1020 // Does a physical scroll
1021 void wxWindow::ScrollWindow(int dx, int dy, const wxRect *rect)
1026 void wxWindow::DoSetVirtualSize( int x, int y )
1028 wxWindowBase::DoSetVirtualSize(x,y);
1029 CocoaCreateNSScrollView();
1030 [m_cocoaNSView setFrameSize:NSMakeSize(m_virtualSize.x,m_virtualSize.y)];
1033 bool wxWindow::SetFont(const wxFont& font)
1035 // FIXME: We may need to handle wx font inheritance.
1036 return wxWindowBase::SetFont(font);
1039 #if 0 // these are used when debugging the algorithm.
1040 static char const * const comparisonresultStrings[] =
1047 class CocoaWindowCompareContext
1049 DECLARE_NO_COPY_CLASS(CocoaWindowCompareContext)
1051 CocoaWindowCompareContext(); // Not implemented
1052 CocoaWindowCompareContext(NSView *target, NSArray *subviews)
1055 // Cocoa sorts subviews in-place.. make a copy
1056 m_subviews = [subviews copy];
1058 ~CocoaWindowCompareContext()
1059 { // release the copy
1060 [m_subviews release];
1063 { return m_target; }
1065 { return m_subviews; }
1066 /* Helper function that returns the comparison based off of the original ordering */
1067 CocoaWindowCompareFunctionResult CompareUsingOriginalOrdering(id first, id second)
1069 NSUInteger firstI = [m_subviews indexOfObjectIdenticalTo:first];
1070 NSUInteger secondI = [m_subviews indexOfObjectIdenticalTo:second];
1071 // NOTE: If either firstI or secondI is NSNotFound then it will be NSIntegerMax and thus will
1072 // likely compare higher than the other view which is reasonable considering the only way that
1073 // can happen is if the subview was added after our call to subviews but before the call to
1074 // sortSubviewsUsingFunction:context:. Thus we don't bother checking. Particularly because
1075 // that case should never occur anyway because that would imply a multi-threaded GUI call
1076 // which is a big no-no with Cocoa.
1078 // Subviews are ordered from back to front meaning one that is already lower will have an lower index.
1079 NSComparisonResult result = (firstI < secondI)
1080 ? NSOrderedAscending /* -1 */
1081 : (firstI > secondI)
1082 ? NSOrderedDescending /* 1 */
1083 : NSOrderedSame /* 0 */;
1085 #if 0 // Enable this if you need to debug the algorithm.
1086 NSLog(@"%@ [%d] %s %@ [%d]\n", first, firstI, comparisonresultStrings[result+1], second, secondI);
1091 /* The subview we are trying to Raise or Lower */
1093 /* A copy of the original array of subviews */
1094 NSArray *m_subviews;
1097 /* Causes Cocoa to raise the target view to the top of the Z-Order by telling the sort function that
1098 * the target view is always higher than every other view. When comparing two views neither of
1099 * which is the target, it returns the correct response based on the original ordering
1101 static CocoaWindowCompareFunctionResult CocoaRaiseWindowCompareFunction(id first, id second, void *ctx)
1103 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
1104 // first should be ordered higher
1105 if(first==compareContext->target())
1106 return NSOrderedDescending;
1107 // second should be ordered higher
1108 if(second==compareContext->target())
1109 return NSOrderedAscending;
1110 return compareContext->CompareUsingOriginalOrdering(first,second);
1113 // Raise the window to the top of the Z order
1114 void wxWindow::Raise()
1116 // wxAutoNSAutoreleasePool pool;
1117 NSView *nsview = GetNSViewForSuperview();
1118 NSView *superview = [nsview superview];
1119 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
1121 [superview sortSubviewsUsingFunction:
1122 CocoaRaiseWindowCompareFunction
1123 context: &compareContext];
1126 /* Causes Cocoa to lower the target view to the bottom of the Z-Order by telling the sort function that
1127 * the target view is always lower than every other view. When comparing two views neither of
1128 * which is the target, it returns the correct response based on the original ordering
1130 static CocoaWindowCompareFunctionResult CocoaLowerWindowCompareFunction(id first, id second, void *ctx)
1132 CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
1133 // first should be ordered lower
1134 if(first==compareContext->target())
1135 return NSOrderedAscending;
1136 // second should be ordered lower
1137 if(second==compareContext->target())
1138 return NSOrderedDescending;
1139 return compareContext->CompareUsingOriginalOrdering(first,second);
1142 // Lower the window to the bottom of the Z order
1143 void wxWindow::Lower()
1145 NSView *nsview = GetNSViewForSuperview();
1146 NSView *superview = [nsview superview];
1147 CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
1150 NSLog(@"Target:\n%@\n", nsview);
1151 NSLog(@"Before:\n%@\n", compareContext.subviews());
1153 [superview sortSubviewsUsingFunction:
1154 CocoaLowerWindowCompareFunction
1155 context: &compareContext];
1157 NSLog(@"After:\n%@\n", [superview subviews]);
1161 bool wxWindow::DoPopupMenu(wxMenu *menu, int x, int y)
1166 // Get the window with the focus
1167 wxWindow *wxWindowBase::DoFindFocus()
1169 // Basically we are somewhat emulating the responder chain here except
1170 // we are only loking for the first responder in the key window or
1171 // upon failing to find one if the main window is different we look
1172 // for the first responder in the main window.
1174 // Note that the firstResponder doesn't necessarily have to be an
1175 // NSView but wxCocoaNSView::GetFromCocoa() will simply return
1176 // NULL unless it finds its argument in its hash map.
1180 NSWindow *keyWindow = [[NSApplication sharedApplication] keyWindow];
1181 win = wxCocoaNSView::GetFromCocoa(static_cast<NSView*>([keyWindow firstResponder]));
1183 return win->GetWxWindow();
1185 NSWindow *mainWindow = [[NSApplication sharedApplication] keyWindow];
1186 if(mainWindow == keyWindow)
1188 win = wxCocoaNSView::GetFromCocoa(static_cast<NSView*>([mainWindow firstResponder]));
1190 return win->GetWxWindow();
1195 /* static */ wxWindow *wxWindowBase::GetCapture()
1198 return wxWindowCocoa::sm_capturedWindow;
1201 wxWindow *wxGetActiveWindow()
1207 wxPoint wxGetMousePosition()
1210 return wxDefaultPosition;
1213 wxMouseState wxGetMouseState()
1220 wxWindow* wxFindWindowAtPointer(wxPoint& pt)
1222 pt = wxGetMousePosition();
1227 // ========================================================================
1228 // wxCocoaTrackingRectManager
1229 // ========================================================================
1231 wxCocoaTrackingRectManager::wxCocoaTrackingRectManager(wxWindow *window)
1234 m_isTrackingRectActive = false;
1235 m_runLoopObserver = NULL;
1236 BuildTrackingRect();
1239 void wxCocoaTrackingRectManager::ClearTrackingRect()
1241 if(m_isTrackingRectActive)
1243 [m_window->GetNSView() removeTrackingRect:m_trackingRectTag];
1244 m_isTrackingRectActive = false;
1246 // If we were doing periodic events we need to clear those too
1247 StopSynthesizingEvents();
1250 void wxCocoaTrackingRectManager::StopSynthesizingEvents()
1252 if(m_runLoopObserver != NULL)
1254 CFRunLoopRemoveObserver([[NSRunLoop currentRunLoop] getCFRunLoop], m_runLoopObserver, kCFRunLoopCommonModes);
1255 CFRelease(m_runLoopObserver);
1256 m_runLoopObserver = NULL;
1260 void wxCocoaTrackingRectManager::BuildTrackingRect()
1262 // Pool here due to lack of one during wx init phase
1263 wxAutoNSAutoreleasePool pool;
1265 wxASSERT_MSG(!m_isTrackingRectActive, wxT("Tracking rect was not cleared"));
1266 if([m_window->GetNSView() window] != nil)
1268 m_trackingRectTag = [m_window->GetNSView() addTrackingRect:[m_window->GetNSView() visibleRect] owner:m_window->GetNSView() userData:NULL assumeInside:NO];
1269 m_isTrackingRectActive = true;
1273 static NSPoint s_lastScreenMouseLocation = NSZeroPoint;
1275 static void SynthesizeMouseMovedEvent(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info)
1277 NSPoint screenMouseLocation = [NSEvent mouseLocation];
1278 if(screenMouseLocation.x != s_lastScreenMouseLocation.x || screenMouseLocation.y != s_lastScreenMouseLocation.y)
1280 wxCocoaNSView *win = reinterpret_cast<wxCocoaNSView*>(info);
1281 win->Cocoa_synthesizeMouseMoved();
1285 void wxCocoaTrackingRectManager::BeginSynthesizingEvents()
1287 CFRunLoopObserverContext observerContext =
1289 , static_cast<wxCocoaNSView*>(m_window)
1294 m_runLoopObserver = CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopBeforeWaiting, TRUE, 0, SynthesizeMouseMovedEvent, &observerContext);
1295 CFRunLoopAddObserver([[NSRunLoop currentRunLoop] getCFRunLoop], m_runLoopObserver, kCFRunLoopCommonModes);
1298 void wxCocoaTrackingRectManager::RebuildTrackingRect()
1300 ClearTrackingRect();
1301 BuildTrackingRect();
1304 wxCocoaTrackingRectManager::~wxCocoaTrackingRectManager()
1306 ClearTrackingRect();
1309 bool wxCocoaTrackingRectManager::IsOwnerOfEvent(NSEvent *anEvent)
1311 return m_isTrackingRectActive && (m_trackingRectTag == [anEvent trackingNumber]);