Fix Raise and Lower to leave all other sibilng views in the order they were in.
[wxWidgets.git] / src / cocoa / window.mm
1 /////////////////////////////////////////////////////////////////////////////
2 // Name:        src/cocoa/window.mm
3 // Purpose:     wxWindowCocoa
4 // Author:      David Elliott
5 // Modified by:
6 // Created:     2002/12/26
7 // RCS-ID:      $Id$
8 // Copyright:   (c) 2002 David Elliott
9 // Licence:     wxWidgets licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #include "wx/wxprec.h"
13
14 #ifndef WX_PRECOMP
15     #include "wx/log.h"
16     #include "wx/window.h"
17     #include "wx/dc.h"
18     #include "wx/utils.h"
19 #endif //WX_PRECOMP
20
21 #include "wx/tooltip.h"
22
23 #include "wx/cocoa/autorelease.h"
24 #include "wx/cocoa/string.h"
25 #include "wx/cocoa/trackingrectmanager.h"
26
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>
36
37 // Turn this on to paint green over the dummy views for debugging
38 #undef WXCOCOA_FILL_DUMMY_VIEW
39
40 #ifdef WXCOCOA_FILL_DUMMY_VIEW
41 #import <AppKit/NSBezierPath.h>
42 #endif //def WXCOCOA_FILL_DUMMY_VIEW
43
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.
49  */
50 #if defined(NSINTEGER_DEFINED)
51 typedef NSComparisonResult CocoaWindowCompareFunctionResult;
52 #else
53 typedef int CocoaWindowCompareFunctionResult;
54 #endif
55
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;
59 @end
60
61 NSPoint CocoaTransformNSViewBoundsToWx(NSView *nsview, NSPoint pointBounds)
62 {
63     wxCHECK_MSG(nsview, pointBounds, wxT("Need to have a Cocoa view to do translation"));
64     if([nsview isFlipped])
65         return pointBounds;
66     NSRect ourBounds = [nsview bounds];
67     return NSMakePoint
68     (   pointBounds.x
69     ,   ourBounds.size.height - pointBounds.y
70     );
71 }
72
73 NSRect CocoaTransformNSViewBoundsToWx(NSView *nsview, NSRect rectBounds)
74 {
75     wxCHECK_MSG(nsview, rectBounds, wxT("Need to have a Cocoa view to do translation"));
76     if([nsview isFlipped])
77         return rectBounds;
78     NSRect ourBounds = [nsview bounds];
79     return NSMakeRect
80     (   rectBounds.origin.x
81     ,   ourBounds.size.height - (rectBounds.origin.y + rectBounds.size.height)
82     ,   rectBounds.size.width
83     ,   rectBounds.size.height
84     );
85 }
86
87 NSPoint CocoaTransformNSViewWxToBounds(NSView *nsview, NSPoint pointWx)
88 {
89     wxCHECK_MSG(nsview, pointWx, wxT("Need to have a Cocoa view to do translation"));
90     if([nsview isFlipped])
91         return pointWx;
92     NSRect ourBounds = [nsview bounds];
93     return NSMakePoint
94     (   pointWx.x
95     ,   ourBounds.size.height - pointWx.y
96     );
97 }
98
99 NSRect CocoaTransformNSViewWxToBounds(NSView *nsview, NSRect rectWx)
100 {
101     wxCHECK_MSG(nsview, rectWx, wxT("Need to have a Cocoa view to do translation"));
102     if([nsview isFlipped])
103         return rectWx;
104     NSRect ourBounds = [nsview bounds];
105     return NSMakeRect
106     (   rectWx.origin.x
107     ,   ourBounds.size.height - (rectWx.origin.y + rectWx.size.height)
108     ,   rectWx.size.width
109     ,   rectWx.size.height
110     );
111 }
112
113 // ========================================================================
114 // wxWindowCocoaHider
115 // ========================================================================
116 class wxWindowCocoaHider: protected wxCocoaNSView
117 {
118     DECLARE_NO_COPY_CLASS(wxWindowCocoaHider)
119 public:
120     wxWindowCocoaHider(wxWindow *owner);
121     virtual ~wxWindowCocoaHider();
122     inline WX_NSView GetNSView() { return m_dummyNSView; }
123 protected:
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
131 private:
132     wxWindowCocoaHider();
133 };
134
135 // ========================================================================
136 // wxWindowCocoaScrollView
137 // ========================================================================
138 class wxWindowCocoaScrollView: protected wxCocoaNSView
139 {
140     DECLARE_NO_COPY_CLASS(wxWindowCocoaScrollView)
141 public:
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;
147     void Encapsulate();
148     void Unencapsulate();
149 protected:
150     wxWindowCocoa *m_owner;
151     WX_NSScrollView m_cocoaNSScrollView;
152     virtual void Cocoa_FrameChanged(void);
153     virtual void Cocoa_synthesizeMouseMoved(void) {}
154 private:
155     wxWindowCocoaScrollView();
156 };
157
158 // ========================================================================
159 // wxDummyNSView
160 // ========================================================================
161 @interface wxDummyNSView : NSView
162 - (NSView *)hitTest:(NSPoint)aPoint;
163 @end
164 WX_DECLARE_GET_OBJC_CLASS(wxDummyNSView,NSView)
165
166 @implementation wxDummyNSView : NSView
167 - (NSView *)hitTest:(NSPoint)aPoint
168 {
169     return nil;
170 }
171
172 @end
173 WX_IMPLEMENT_GET_OBJC_CLASS(wxDummyNSView,NSView)
174
175 // ========================================================================
176 // wxWindowCocoaHider
177 // ========================================================================
178 wxWindowCocoaHider::wxWindowCocoaHider(wxWindow *owner)
179 :   m_owner(owner)
180 {
181     wxASSERT(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);
187 }
188
189 wxWindowCocoaHider::~wxWindowCocoaHider()
190 {
191     DisassociateNSView(m_dummyNSView);
192     [m_dummyNSView release];
193 }
194
195 void wxWindowCocoaHider::Cocoa_FrameChanged(void)
196 {
197     // Keep the real window in synch with the dummy
198     wxASSERT(m_dummyNSView);
199     [m_owner->GetNSViewForHiding() setFrame:[m_dummyNSView frame]];
200 }
201
202
203 #ifdef WXCOCOA_FILL_DUMMY_VIEW
204 bool wxWindowCocoaHider::Cocoa_drawRect(const NSRect& rect)
205 {
206     NSBezierPath *bezpath = [NSBezierPath bezierPathWithRect:rect];
207     [[NSColor greenColor] set];
208     [bezpath stroke];
209     [bezpath fill];
210     return true;
211 }
212 #endif //def WXCOCOA_FILL_DUMMY_VIEW
213
214 // ========================================================================
215 // wxFlippedNSClipView
216 // ========================================================================
217 @interface wxFlippedNSClipView : NSClipView
218 - (BOOL)isFlipped;
219 @end
220 WX_DECLARE_GET_OBJC_CLASS(wxFlippedNSClipView,NSClipView)
221
222 @implementation wxFlippedNSClipView : NSClipView
223 - (BOOL)isFlipped
224 {
225     return YES;
226 }
227
228 @end
229 WX_IMPLEMENT_GET_OBJC_CLASS(wxFlippedNSClipView,NSClipView)
230
231 // ========================================================================
232 // wxWindowCocoaScrollView
233 // ========================================================================
234 wxWindowCocoaScrollView::wxWindowCocoaScrollView(wxWindow *owner)
235 :   m_owner(owner)
236 {
237     wxAutoNSAutoreleasePool pool;
238     wxASSERT(owner);
239     wxASSERT(owner->GetNSView());
240     m_cocoaNSScrollView = [[NSScrollView alloc]
241         initWithFrame:[owner->GetNSView() frame]];
242     AssociateNSView(m_cocoaNSScrollView);
243
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];
250
251     [m_cocoaNSScrollView setBackgroundColor: [NSColor windowBackgroundColor]];
252     [m_cocoaNSScrollView setHasHorizontalScroller: YES];
253     [m_cocoaNSScrollView setHasVerticalScroller: YES];
254     Encapsulate();
255 }
256
257 void wxWindowCocoaScrollView::Encapsulate()
258 {
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
269 }
270
271 void wxWindowCocoaScrollView::Unencapsulate()
272 {
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];
277 }
278
279 wxWindowCocoaScrollView::~wxWindowCocoaScrollView()
280 {
281     DisassociateNSView(m_cocoaNSScrollView);
282     [m_cocoaNSScrollView release];
283 }
284
285 void wxWindowCocoaScrollView::ClientSizeToSize(int &width, int &height)
286 {
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;
294 }
295
296 void wxWindowCocoaScrollView::DoGetClientSize(int *x, int *y) const
297 {
298     NSSize nssize = [m_cocoaNSScrollView contentSize];
299     if(x)
300         *x = (int)nssize.width;
301     if(y)
302         *y = (int)nssize.height;
303 }
304
305 void wxWindowCocoaScrollView::Cocoa_FrameChanged(void)
306 {
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);
311 }
312
313 // ========================================================================
314 // wxWindowCocoa
315 // ========================================================================
316 // normally the base classes aren't included, but wxWindow is special
317 #ifdef __WXUNIVERSAL__
318 IMPLEMENT_ABSTRACT_CLASS(wxWindowCocoa, wxWindowBase)
319 #else
320 IMPLEMENT_DYNAMIC_CLASS(wxWindow, wxWindowBase)
321 #endif
322
323 BEGIN_EVENT_TABLE(wxWindowCocoa, wxWindowBase)
324 END_EVENT_TABLE()
325
326 wxWindow *wxWindowCocoa::sm_capturedWindow = NULL;
327
328 // Constructor
329 void wxWindowCocoa::Init()
330 {
331     m_cocoaNSView = NULL;
332     m_cocoaHider = NULL;
333     m_wxCocoaScrollView = NULL;
334     m_isBeingDeleted = false;
335     m_isInPaint = false;
336     m_visibleTrackingRectManager = NULL;
337 }
338
339 // Constructor
340 bool wxWindow::Create(wxWindow *parent, wxWindowID winid,
341            const wxPoint& pos,
342            const wxSize& size,
343            long style,
344            const wxString& name)
345 {
346     if(!CreateBase(parent,winid,pos,size,style,wxDefaultValidator,name))
347         return false;
348
349     // TODO: create the window
350     m_cocoaNSView = NULL;
351     SetNSView([[WX_GET_OBJC_CLASS(WXNSView) alloc] initWithFrame: MakeDefaultNSRect(size)]);
352     [m_cocoaNSView release];
353
354     if (m_parent)
355     {
356         m_parent->AddChild(this);
357         m_parent->CocoaAddChild(this);
358         SetInitialFrameRect(pos,size);
359     }
360
361     return true;
362 }
363
364 // Destructor
365 wxWindow::~wxWindow()
366 {
367     wxAutoNSAutoreleasePool pool;
368     DestroyChildren();
369
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();
374     delete m_cocoaHider;
375     delete m_wxCocoaScrollView;
376     if(m_cocoaNSView)
377         SendDestroyEvent();
378     SetNSView(NULL);
379 }
380
381 void wxWindowCocoa::CocoaAddChild(wxWindowCocoa *child)
382 {
383     NSView *childView = child->GetNSViewForSuperview();
384
385     wxASSERT(childView);
386     [m_cocoaNSView addSubview: childView];
387     child->m_isShown = !m_cocoaHider;
388 }
389
390 void wxWindowCocoa::CocoaRemoveFromParent(void)
391 {
392     [GetNSViewForSuperview() removeFromSuperview];
393 }
394
395 void wxWindowCocoa::SetNSView(WX_NSView cocoaNSView)
396 {
397     // Clear the visible area tracking rect if we have one.
398     delete m_visibleTrackingRectManager;
399     m_visibleTrackingRectManager = NULL;
400
401     bool need_debug = cocoaNSView || m_cocoaNSView;
402     if(need_debug) wxLogTrace(wxTRACE_COCOA_RetainRelease,wxT("wxWindowCocoa=%p::SetNSView [m_cocoaNSView=%p retainCount]=%d"),this,m_cocoaNSView,[m_cocoaNSView retainCount]);
403     DisassociateNSView(m_cocoaNSView);
404     [cocoaNSView retain];
405     [m_cocoaNSView release];
406     m_cocoaNSView = cocoaNSView;
407     AssociateNSView(m_cocoaNSView);
408     if(need_debug) wxLogTrace(wxTRACE_COCOA_RetainRelease,wxT("wxWindowCocoa=%p::SetNSView [cocoaNSView=%p retainCount]=%d"),this,cocoaNSView,[cocoaNSView retainCount]);
409 }
410
411 WX_NSView wxWindowCocoa::GetNSViewForSuperview() const
412 {
413     return m_cocoaHider
414         ?   m_cocoaHider->GetNSView()
415         :   m_wxCocoaScrollView
416             ?   m_wxCocoaScrollView->GetNSScrollView()
417             :   m_cocoaNSView;
418 }
419
420 WX_NSView wxWindowCocoa::GetNSViewForHiding() const
421 {
422     return m_wxCocoaScrollView
423         ?   m_wxCocoaScrollView->GetNSScrollView()
424         :   m_cocoaNSView;
425 }
426
427 NSPoint wxWindowCocoa::CocoaTransformBoundsToWx(NSPoint pointBounds)
428 {
429     // TODO: Handle scrolling offset
430     return CocoaTransformNSViewBoundsToWx(GetNSView(), pointBounds);
431 }
432
433 NSRect wxWindowCocoa::CocoaTransformBoundsToWx(NSRect rectBounds)
434 {
435     // TODO: Handle scrolling offset
436     return CocoaTransformNSViewBoundsToWx(GetNSView(), rectBounds);
437 }
438
439 NSPoint wxWindowCocoa::CocoaTransformWxToBounds(NSPoint pointWx)
440 {
441     // TODO: Handle scrolling offset
442     return CocoaTransformNSViewWxToBounds(GetNSView(), pointWx);
443 }
444
445 NSRect wxWindowCocoa::CocoaTransformWxToBounds(NSRect rectWx)
446 {
447     // TODO: Handle scrolling offset
448     return CocoaTransformNSViewWxToBounds(GetNSView(), rectWx);
449 }
450
451 WX_NSAffineTransform wxWindowCocoa::CocoaGetWxToBoundsTransform()
452 {
453     // TODO: Handle scrolling offset
454     NSAffineTransform *transform = wxDC::CocoaGetWxToBoundsTransform([GetNSView() isFlipped], [GetNSView() bounds].size.height);
455     return transform;
456 }
457
458 bool wxWindowCocoa::Cocoa_drawRect(const NSRect &rect)
459 {
460     wxLogTrace(wxTRACE_COCOA,wxT("Cocoa_drawRect"));
461     // Recursion can happen if the event loop runs from within the paint
462     // handler.  For instance, if an assertion dialog is shown.
463     // FIXME: This seems less than ideal.
464     if(m_isInPaint)
465     {
466         wxLogDebug(wxT("Paint event recursion!"));
467         return false;
468     }
469     m_isInPaint = true;
470
471     // Set m_updateRegion
472     const NSRect *rects = &rect; // The bounding box of the region
473     NSInteger countRects = 1;
474     // Try replacing the larger rectangle with a list of smaller ones:
475     if ([GetNSView() respondsToSelector:@selector(getRectsBeingDrawn:count:)])
476         [GetNSView() getRectsBeingDrawn:&rects count:&countRects];
477
478     NSRect *transformedRects = (NSRect*)malloc(sizeof(NSRect)*countRects);
479     for(int i=0; i<countRects; i++)
480     {
481         transformedRects[i] = CocoaTransformBoundsToWx(rects[i]);
482     }
483     m_updateRegion = wxRegion(transformedRects,countRects);
484     free(transformedRects);
485
486     wxPaintEvent event(m_windowId);
487     event.SetEventObject(this);
488     bool ret = GetEventHandler()->ProcessEvent(event);
489     m_isInPaint = false;
490     return ret;
491 }
492
493 void wxWindowCocoa::InitMouseEvent(wxMouseEvent& event, WX_NSEvent cocoaEvent)
494 {
495     wxASSERT_MSG([m_cocoaNSView window]==[cocoaEvent window],wxT("Mouse event for different NSWindow"));
496     // Mouse events happen at the NSWindow level so we need to convert
497     // into our bounds coordinates then convert to wx coordinates.
498     NSPoint cocoaPoint = [m_cocoaNSView convertPoint:[(NSEvent*)cocoaEvent locationInWindow] fromView:nil];
499     NSPoint pointWx = CocoaTransformBoundsToWx(cocoaPoint);
500     // FIXME: Should we be adjusting for client area origin?
501     const wxPoint &clientorigin = GetClientAreaOrigin();
502     event.m_x = (wxCoord)pointWx.x - clientorigin.x;
503     event.m_y = (wxCoord)pointWx.y - clientorigin.y;
504
505     event.m_shiftDown = [cocoaEvent modifierFlags] & NSShiftKeyMask;
506     event.m_controlDown = [cocoaEvent modifierFlags] & NSControlKeyMask;
507     event.m_altDown = [cocoaEvent modifierFlags] & NSAlternateKeyMask;
508     event.m_metaDown = [cocoaEvent modifierFlags] & NSCommandKeyMask;
509
510     // TODO: set timestamp?
511     event.SetEventObject(this);
512     event.SetId(GetId());
513 }
514
515 bool wxWindowCocoa::Cocoa_mouseMoved(WX_NSEvent theEvent)
516 {
517     wxMouseEvent event(wxEVT_MOTION);
518     InitMouseEvent(event,theEvent);
519     wxLogTrace(wxTRACE_COCOA,wxT("wxWindow=%p::Cocoa_mouseMoved @%d,%d"),this,event.m_x,event.m_y);
520     return GetEventHandler()->ProcessEvent(event);
521 }
522
523 void wxWindowCocoa::Cocoa_synthesizeMouseMoved()
524 {
525     wxMouseEvent event(wxEVT_MOTION);
526     NSWindow *window = [GetNSView() window];
527     NSPoint locationInWindow = [window mouseLocationOutsideOfEventStream];
528     NSPoint cocoaPoint = [m_cocoaNSView convertPoint:locationInWindow fromView:nil];
529
530     NSPoint pointWx = CocoaTransformBoundsToWx(cocoaPoint);
531     // FIXME: Should we be adjusting for client area origin?
532     const wxPoint &clientorigin = GetClientAreaOrigin();
533     event.m_x = (wxCoord)pointWx.x - clientorigin.x;
534     event.m_y = (wxCoord)pointWx.y - clientorigin.y;
535
536     // TODO: Handle shift, control, alt, meta flags
537     event.SetEventObject(this);
538     event.SetId(GetId());
539
540     wxLogTrace(wxTRACE_COCOA,wxT("wxwin=%p Synthesized Mouse Moved @%d,%d"),this,event.m_x,event.m_y);
541     GetEventHandler()->ProcessEvent(event);
542 }
543
544 bool wxWindowCocoa::Cocoa_mouseEntered(WX_NSEvent theEvent)
545 {
546     if(m_visibleTrackingRectManager != NULL && m_visibleTrackingRectManager->IsOwnerOfEvent(theEvent))
547     {
548         m_visibleTrackingRectManager->BeginSynthesizingEvents();
549
550         // Although we synthesize the mouse moved events we don't poll for them but rather send them only when
551         // some other event comes in.  That other event is (guess what) mouse moved events that will be sent
552         // to the NSWindow which will forward them on to the first responder.  We are not likely to be the
553         // first responder, so the mouseMoved: events are effectively discarded.
554         [[GetNSView() window] setAcceptsMouseMovedEvents:YES];
555
556         wxMouseEvent event(wxEVT_ENTER_WINDOW);
557         InitMouseEvent(event,theEvent);
558         wxLogTrace(wxTRACE_COCOA,wxT("wxwin=%p Mouse Entered @%d,%d"),this,event.m_x,event.m_y);
559         return GetEventHandler()->ProcessEvent(event);
560     }
561     else
562         return false;
563 }
564
565 bool wxWindowCocoa::Cocoa_mouseExited(WX_NSEvent theEvent)
566 {
567     if(m_visibleTrackingRectManager != NULL && m_visibleTrackingRectManager->IsOwnerOfEvent(theEvent))
568     {
569         m_visibleTrackingRectManager->StopSynthesizingEvents();
570
571         wxMouseEvent event(wxEVT_LEAVE_WINDOW);
572         InitMouseEvent(event,theEvent);
573         wxLogTrace(wxTRACE_COCOA,wxT("wxwin=%p Mouse Exited @%d,%d"),this,event.m_x,event.m_y);
574         return GetEventHandler()->ProcessEvent(event);
575     }
576     else
577         return false;
578 }
579
580 bool wxWindowCocoa::Cocoa_mouseDown(WX_NSEvent theEvent)
581 {
582     wxMouseEvent event([theEvent clickCount]<2?wxEVT_LEFT_DOWN:wxEVT_LEFT_DCLICK);
583     InitMouseEvent(event,theEvent);
584     wxLogTrace(wxTRACE_COCOA,wxT("Mouse Down @%d,%d num clicks=%d"),event.m_x,event.m_y,[theEvent clickCount]);
585     return GetEventHandler()->ProcessEvent(event);
586 }
587
588 bool wxWindowCocoa::Cocoa_mouseDragged(WX_NSEvent theEvent)
589 {
590     wxMouseEvent event(wxEVT_MOTION);
591     InitMouseEvent(event,theEvent);
592     event.m_leftDown = true;
593     wxLogTrace(wxTRACE_COCOA,wxT("Mouse Drag @%d,%d"),event.m_x,event.m_y);
594     return GetEventHandler()->ProcessEvent(event);
595 }
596
597 bool wxWindowCocoa::Cocoa_mouseUp(WX_NSEvent theEvent)
598 {
599     wxMouseEvent event(wxEVT_LEFT_UP);
600     InitMouseEvent(event,theEvent);
601     wxLogTrace(wxTRACE_COCOA,wxT("Mouse Up @%d,%d"),event.m_x,event.m_y);
602     return GetEventHandler()->ProcessEvent(event);
603 }
604
605 bool wxWindowCocoa::Cocoa_rightMouseDown(WX_NSEvent theEvent)
606 {
607     wxMouseEvent event([theEvent clickCount]<2?wxEVT_RIGHT_DOWN:wxEVT_RIGHT_DCLICK);
608     InitMouseEvent(event,theEvent);
609     wxLogDebug(wxT("Mouse Down @%d,%d num clicks=%d"),event.m_x,event.m_y,[theEvent clickCount]);
610     return GetEventHandler()->ProcessEvent(event);
611 }
612
613 bool wxWindowCocoa::Cocoa_rightMouseDragged(WX_NSEvent theEvent)
614 {
615     wxMouseEvent event(wxEVT_MOTION);
616     InitMouseEvent(event,theEvent);
617     event.m_rightDown = true;
618     wxLogDebug(wxT("Mouse Drag @%d,%d"),event.m_x,event.m_y);
619     return GetEventHandler()->ProcessEvent(event);
620 }
621
622 bool wxWindowCocoa::Cocoa_rightMouseUp(WX_NSEvent theEvent)
623 {
624     wxMouseEvent event(wxEVT_RIGHT_UP);
625     InitMouseEvent(event,theEvent);
626     wxLogDebug(wxT("Mouse Up @%d,%d"),event.m_x,event.m_y);
627     return GetEventHandler()->ProcessEvent(event);
628 }
629
630 bool wxWindowCocoa::Cocoa_otherMouseDown(WX_NSEvent theEvent)
631 {
632     return false;
633 }
634
635 bool wxWindowCocoa::Cocoa_otherMouseDragged(WX_NSEvent theEvent)
636 {
637     return false;
638 }
639
640 bool wxWindowCocoa::Cocoa_otherMouseUp(WX_NSEvent theEvent)
641 {
642     return false;
643 }
644
645 void wxWindowCocoa::Cocoa_FrameChanged(void)
646 {
647     wxLogTrace(wxTRACE_COCOA,wxT("wxWindow=%p::Cocoa_FrameChanged"),this);
648     if(m_visibleTrackingRectManager != NULL)
649         m_visibleTrackingRectManager->RebuildTrackingRect();
650     wxSizeEvent event(GetSize(), m_windowId);
651     event.SetEventObject(this);
652     GetEventHandler()->ProcessEvent(event);
653 }
654
655 bool wxWindowCocoa::Cocoa_resetCursorRects()
656 {
657     wxLogTrace(wxTRACE_COCOA,wxT("wxWindow=%p::Cocoa_resetCursorRects"),this);
658     if(m_visibleTrackingRectManager != NULL)
659         m_visibleTrackingRectManager->RebuildTrackingRect();
660
661     if(!m_cursor.GetNSCursor())
662         return false;
663
664     [GetNSView() addCursorRect: [GetNSView() visibleRect]  cursor: m_cursor.GetNSCursor()];
665
666     return true;
667 }
668
669 bool wxWindowCocoa::Cocoa_viewDidMoveToWindow()
670 {
671     wxLogTrace(wxTRACE_COCOA,wxT("wxWindow=%p::viewDidMoveToWindow"),this);
672     // Set up new tracking rects.  I am reasonably sure the new window must be set before doing this.
673     if(m_visibleTrackingRectManager != NULL)
674         m_visibleTrackingRectManager->BuildTrackingRect();
675     return false;
676 }
677
678 bool wxWindowCocoa::Cocoa_viewWillMoveToWindow(WX_NSWindow newWindow)
679 {
680     wxLogTrace(wxTRACE_COCOA,wxT("wxWindow=%p::viewWillMoveToWindow:%p"),this, newWindow);
681     // Clear tracking rects.  It is imperative this be done before the new window is set.
682     if(m_visibleTrackingRectManager != NULL)
683         m_visibleTrackingRectManager->ClearTrackingRect();
684     return false;
685 }
686
687 bool wxWindow::Close(bool force)
688 {
689     // The only reason this function exists is that it is virtual and
690     // wxTopLevelWindowCocoa will override it.
691     return wxWindowBase::Close(force);
692 }
693
694 void wxWindow::CocoaReplaceView(WX_NSView oldView, WX_NSView newView)
695 {
696     [[oldView superview] replaceSubview:oldView with:newView];
697 }
698
699 void wxWindow::DoEnable(bool enable)
700 {
701         CocoaSetEnabled(enable);
702 }
703
704 bool wxWindow::Show(bool show)
705 {
706     wxAutoNSAutoreleasePool pool;
707     // If the window is marked as visible, then it shouldn't have a dummy view
708     // If the window is marked hidden, then it should have a dummy view
709     // wxSpinCtrl (generic) abuses m_isShown, don't use it for any logic
710 //    wxASSERT_MSG( (m_isShown && !m_dummyNSView) || (!m_isShown && m_dummyNSView),wxT("wxWindow: m_isShown does not agree with m_dummyNSView"));
711     // Return false if there isn't a window to show or hide
712     NSView *cocoaView = GetNSViewForHiding();
713     if(!cocoaView)
714         return false;
715     if(show)
716     {
717         // If state isn't changing, return false
718         if(!m_cocoaHider)
719             return false;
720         CocoaReplaceView(m_cocoaHider->GetNSView(), cocoaView);
721         wxASSERT(![m_cocoaHider->GetNSView() superview]);
722         delete m_cocoaHider;
723         m_cocoaHider = NULL;
724         wxASSERT([cocoaView superview]);
725     }
726     else
727     {
728         // If state isn't changing, return false
729         if(m_cocoaHider)
730             return false;
731         m_cocoaHider = new wxWindowCocoaHider(this);
732         // NOTE: replaceSubview:with will cause m_cocaNSView to be
733         // (auto)released which balances out addSubview
734         CocoaReplaceView(cocoaView, m_cocoaHider->GetNSView());
735         // m_coocaNSView is now only retained by us
736         wxASSERT([m_cocoaHider->GetNSView() superview]);
737         wxASSERT(![cocoaView superview]);
738     }
739     m_isShown = show;
740     return true;
741 }
742
743 void wxWindowCocoa::DoSetSize(int x, int y, int width, int height, int sizeFlags)
744 {
745     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":".");
746     int currentX, currentY;
747     int currentW, currentH;
748     DoGetPosition(&currentX, &currentY);
749     DoGetSize(&currentW, &currentH);
750     if((x==-1) && !(sizeFlags&wxSIZE_ALLOW_MINUS_ONE))
751         x=currentX;
752     if((y==-1) && !(sizeFlags&wxSIZE_ALLOW_MINUS_ONE))
753         y=currentY;
754
755     AdjustForParentClientOrigin(x,y,sizeFlags);
756
757     wxSize size(wxDefaultSize);
758
759     if((width==-1)&&!(sizeFlags&wxSIZE_ALLOW_MINUS_ONE))
760     {
761         if(sizeFlags&wxSIZE_AUTO_WIDTH)
762         {
763             size=DoGetBestSize();
764             width=size.x;
765         }
766         else
767             width=currentW;
768     }
769     if((height==-1)&&!(sizeFlags&wxSIZE_ALLOW_MINUS_ONE))
770     {
771         if(sizeFlags&wxSIZE_AUTO_HEIGHT)
772         {
773             if(size.x==-1)
774                 size=DoGetBestSize();
775             height=size.y;
776         }
777         else
778             height=currentH;
779     }
780     DoMoveWindow(x,y,width,height);
781 }
782
783 #if wxUSE_TOOLTIPS
784
785 void wxWindowCocoa::DoSetToolTip( wxToolTip *tip )
786 {
787     wxWindowBase::DoSetToolTip(tip);
788
789     if ( m_tooltip )
790     {
791         m_tooltip->SetWindow((wxWindow *)this);
792     }
793 }
794
795 #endif
796
797 void wxWindowCocoa::DoMoveWindow(int x, int y, int width, int height)
798 {
799     wxAutoNSAutoreleasePool pool;
800     wxLogTrace(wxTRACE_COCOA_Window_Size,wxT("wxWindow=%p::DoMoveWindow(%d,%d,%d,%d)"),this,x,y,width,height);
801
802     NSView *nsview = GetNSViewForSuperview();
803     NSView *superview = [nsview superview];
804
805     wxCHECK_RET(GetParent(), wxT("Window can only be placed correctly when it has a parent"));
806
807     NSRect oldFrameRect = [nsview frame];
808     NSRect newFrameRect = GetParent()->CocoaTransformWxToBounds(NSMakeRect(x,y,width,height));
809     [nsview setFrame:newFrameRect];
810     // Be sure to redraw the parent to reflect the changed position
811     [superview setNeedsDisplayInRect:oldFrameRect];
812     [superview setNeedsDisplayInRect:newFrameRect];
813 }
814
815 void wxWindowCocoa::SetInitialFrameRect(const wxPoint& pos, const wxSize& size)
816 {
817     NSView *nsview = GetNSViewForSuperview();
818     NSView *superview = [nsview superview];
819     wxCHECK_RET(superview,wxT("NSView does not have a superview"));
820     wxCHECK_RET(GetParent(), wxT("Window can only be placed correctly when it has a parent"));
821     NSRect frameRect = [nsview frame];
822     if(size.x!=-1)
823         frameRect.size.width = size.x;
824     if(size.y!=-1)
825         frameRect.size.height = size.y;
826     frameRect.origin.x = pos.x;
827     frameRect.origin.y = pos.y;
828     // Tell Cocoa to change the margin between the bottom of the superview
829     // and the bottom of the control.  Keeps the control pinned to the top
830     // of its superview so that its position in the wxWidgets coordinate
831     // system doesn't change.
832     if(![superview isFlipped])
833         [nsview setAutoresizingMask: NSViewMinYMargin];
834     // MUST set the mask before setFrame: which can generate a size event
835     // and cause a scroller to be added!
836     frameRect = GetParent()->CocoaTransformWxToBounds(frameRect);
837     [nsview setFrame: frameRect];
838 }
839
840 // Get total size
841 void wxWindow::DoGetSize(int *w, int *h) const
842 {
843     NSRect cocoaRect = [GetNSViewForSuperview() frame];
844     if(w)
845         *w=(int)cocoaRect.size.width;
846     if(h)
847         *h=(int)cocoaRect.size.height;
848     wxLogTrace(wxTRACE_COCOA_Window_Size,wxT("wxWindow=%p::DoGetSize = (%d,%d)"),this,(int)cocoaRect.size.width,(int)cocoaRect.size.height);
849 }
850
851 void wxWindow::DoGetPosition(int *x, int *y) const
852 {
853     NSView *nsview = GetNSViewForSuperview();
854
855     NSRect cocoaRect = [nsview frame];
856     NSRect rectWx = GetParent()->CocoaTransformBoundsToWx(cocoaRect);
857     if(x)
858         *x=(int)rectWx.origin.x;
859     if(y)
860         *y=(int)rectWx.origin.y;
861     wxLogTrace(wxTRACE_COCOA_Window_Size,wxT("wxWindow=%p::DoGetPosition = (%d,%d)"),this,(int)cocoaRect.origin.x,(int)cocoaRect.origin.y);
862 }
863
864 WXWidget wxWindow::GetHandle() const
865 {
866     return m_cocoaNSView;
867 }
868
869 wxWindow* wxWindow::GetWxWindow() const
870 {
871     return (wxWindow*) this;
872 }
873
874 void wxWindow::Refresh(bool eraseBack, const wxRect *rect)
875 {
876     [m_cocoaNSView setNeedsDisplay:YES];
877 }
878
879 void wxWindow::SetFocus()
880 {
881     if([GetNSView() acceptsFirstResponder])
882         [[GetNSView() window] makeFirstResponder: GetNSView()];
883 }
884
885 void wxWindow::DoCaptureMouse()
886 {
887     // TODO
888     sm_capturedWindow = this;
889 }
890
891 void wxWindow::DoReleaseMouse()
892 {
893     // TODO
894     sm_capturedWindow = NULL;
895 }
896
897 void wxWindow::DoScreenToClient(int *x, int *y) const
898 {
899     // TODO
900 }
901
902 void wxWindow::DoClientToScreen(int *x, int *y) const
903 {
904     // TODO
905 }
906
907 // Get size *available for subwindows* i.e. excluding menu bar etc.
908 void wxWindow::DoGetClientSize(int *x, int *y) const
909 {
910     wxLogTrace(wxTRACE_COCOA,wxT("DoGetClientSize:"));
911     if(m_wxCocoaScrollView)
912         m_wxCocoaScrollView->DoGetClientSize(x,y);
913     else
914         wxWindowCocoa::DoGetSize(x,y);
915 }
916
917 void wxWindow::DoSetClientSize(int width, int height)
918 {
919     wxLogTrace(wxTRACE_COCOA_Window_Size,wxT("DoSetClientSize=(%d,%d)"),width,height);
920     if(m_wxCocoaScrollView)
921         m_wxCocoaScrollView->ClientSizeToSize(width,height);
922     CocoaSetWxWindowSize(width,height);
923 }
924
925 void wxWindow::CocoaSetWxWindowSize(int width, int height)
926 {
927     wxWindowCocoa::DoSetSize(wxDefaultCoord,wxDefaultCoord,width,height,wxSIZE_USE_EXISTING);
928 }
929
930 void wxWindow::SetLabel(const wxString& WXUNUSED(label))
931 {
932     // Intentional no-op.
933 }
934
935 wxString wxWindow::GetLabel() const
936 {
937     // General Get/Set of labels is implemented in wxControlBase
938     wxLogDebug(wxT("wxWindow::GetLabel: Should be overridden if needed."));
939     return wxEmptyString;
940 }
941
942 int wxWindow::GetCharHeight() const
943 {
944     // TODO
945     return 0;
946 }
947
948 int wxWindow::GetCharWidth() const
949 {
950     // TODO
951     return 0;
952 }
953
954 void wxWindow::GetTextExtent(const wxString& string, int *x, int *y,
955         int *descent, int *externalLeading, const wxFont *theFont) const
956 {
957     // TODO
958 }
959
960 // Coordinates relative to the window
961 void wxWindow::WarpPointer (int x_pos, int y_pos)
962 {
963     // TODO
964 }
965
966 int wxWindow::GetScrollPos(int orient) const
967 {
968     // TODO
969     return 0;
970 }
971
972 // This now returns the whole range, not just the number
973 // of positions that we can scroll.
974 int wxWindow::GetScrollRange(int orient) const
975 {
976     // TODO
977     return 0;
978 }
979
980 int wxWindow::GetScrollThumb(int orient) const
981 {
982     // TODO
983     return 0;
984 }
985
986 void wxWindow::SetScrollPos(int orient, int pos, bool refresh)
987 {
988     // TODO
989 }
990
991 void wxWindow::CocoaCreateNSScrollView()
992 {
993     if(!m_wxCocoaScrollView)
994     {
995         m_wxCocoaScrollView = new wxWindowCocoaScrollView(this);
996     }
997 }
998
999 // New function that will replace some of the above.
1000 void wxWindow::SetScrollbar(int orient, int pos, int thumbVisible,
1001     int range, bool refresh)
1002 {
1003     CocoaCreateNSScrollView();
1004     // TODO
1005 }
1006
1007 // Does a physical scroll
1008 void wxWindow::ScrollWindow(int dx, int dy, const wxRect *rect)
1009 {
1010     // TODO
1011 }
1012
1013 void wxWindow::DoSetVirtualSize( int x, int y )
1014 {
1015     wxWindowBase::DoSetVirtualSize(x,y);
1016     CocoaCreateNSScrollView();
1017     [m_cocoaNSView setFrameSize:NSMakeSize(m_virtualSize.x,m_virtualSize.y)];
1018 }
1019
1020 bool wxWindow::SetFont(const wxFont& font)
1021 {
1022     // TODO
1023     return true;
1024 }
1025
1026 #if 0 // these are used when debugging the algorithm.
1027 static char const * const comparisonresultStrings[] =
1028 {   "<"
1029 ,   "=="
1030 ,   ">"
1031 };
1032 #endif
1033
1034 class CocoaWindowCompareContext
1035 {
1036     DECLARE_NO_COPY_CLASS(CocoaWindowCompareContext)
1037 public:
1038     CocoaWindowCompareContext(); // Not implemented
1039     CocoaWindowCompareContext(NSView *target, NSArray *subviews)
1040     {
1041         m_target = target;
1042         // Cocoa sorts subviews in-place.. make a copy
1043         m_subviews = [subviews copy];
1044     }
1045     ~CocoaWindowCompareContext()
1046     {   // release the copy
1047         [m_subviews release];
1048     }
1049     NSView* target()
1050     {   return m_target; }
1051     NSArray* subviews()
1052     {   return m_subviews; }
1053     /* Helper function that returns the comparison based off of the original ordering */
1054     CocoaWindowCompareFunctionResult CompareUsingOriginalOrdering(id first, id second)
1055     {
1056         NSUInteger firstI = [m_subviews indexOfObjectIdenticalTo:first];
1057         NSUInteger secondI = [m_subviews indexOfObjectIdenticalTo:second];
1058         // NOTE: If either firstI or secondI is NSNotFound then it will be NSIntegerMax and thus will
1059         // likely compare higher than the other view which is reasonable considering the only way that
1060         // can happen is if the subview was added after our call to subviews but before the call to
1061         // sortSubviewsUsingFunction:context:.  Thus we don't bother checking.  Particularly because
1062         // that case should never occur anyway because that would imply a multi-threaded GUI call
1063         // which is a big no-no with Cocoa.
1064
1065         // Subviews are ordered from back to front meaning one that is already lower will have an lower index.
1066         NSComparisonResult result = (firstI < secondI)
1067             ?   NSOrderedAscending /* -1 */
1068             :   (firstI > secondI)
1069                 ?   NSOrderedDescending /* 1 */
1070                 :   NSOrderedSame /* 0 */;
1071
1072 #if 0 // Enable this if you need to debug the algorithm.
1073         NSLog(@"%@ [%d] %s %@ [%d]\n", first, firstI, comparisonresultStrings[result+1], second, secondI);
1074 #endif
1075         return result;
1076     }
1077 private:
1078     /* The subview we are trying to Raise or Lower */
1079     NSView *m_target;
1080     /* A copy of the original array of subviews */
1081     NSArray *m_subviews;
1082 };
1083
1084 /* Causes Cocoa to raise the target view to the top of the Z-Order by telling the sort function that
1085  * the target view is always higher than every other view.  When comparing two views neither of
1086  * which is the target, it returns the correct response based on the original ordering
1087  */
1088 static CocoaWindowCompareFunctionResult CocoaRaiseWindowCompareFunction(id first, id second, void *ctx)
1089 {
1090     CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
1091     // first should be ordered higher
1092     if(first==compareContext->target())
1093         return NSOrderedDescending;
1094     // second should be ordered higher
1095     if(second==compareContext->target())
1096         return NSOrderedAscending;
1097     return compareContext->CompareUsingOriginalOrdering(first,second);
1098 }
1099
1100 // Raise the window to the top of the Z order
1101 void wxWindow::Raise()
1102 {
1103 //    wxAutoNSAutoreleasePool pool;
1104     NSView *nsview = GetNSViewForSuperview();
1105     NSView *superview = [nsview superview];
1106     CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
1107
1108     [superview sortSubviewsUsingFunction:
1109             CocoaRaiseWindowCompareFunction
1110         context: &compareContext];
1111 }
1112
1113 /* Causes Cocoa to lower the target view to the bottom of the Z-Order by telling the sort function that
1114  * the target view is always lower than every other view.  When comparing two views neither of
1115  * which is the target, it returns the correct response based on the original ordering
1116  */
1117 static CocoaWindowCompareFunctionResult CocoaLowerWindowCompareFunction(id first, id second, void *ctx)
1118 {
1119     CocoaWindowCompareContext *compareContext = (CocoaWindowCompareContext*)ctx;
1120     // first should be ordered lower
1121     if(first==compareContext->target())
1122         return NSOrderedAscending;
1123     // second should be ordered lower
1124     if(second==compareContext->target())
1125         return NSOrderedDescending;
1126     return compareContext->CompareUsingOriginalOrdering(first,second);
1127 }
1128
1129 // Lower the window to the bottom of the Z order
1130 void wxWindow::Lower()
1131 {
1132     NSView *nsview = GetNSViewForSuperview();
1133     NSView *superview = [nsview superview];
1134     CocoaWindowCompareContext compareContext(nsview, [superview subviews]);
1135
1136 #if 0
1137     NSLog(@"Target:\n%@\n", nsview);
1138     NSLog(@"Before:\n%@\n", compareContext.subviews());
1139 #endif
1140     [superview sortSubviewsUsingFunction:
1141             CocoaLowerWindowCompareFunction
1142         context: &compareContext];
1143 #if 0
1144     NSLog(@"After:\n%@\n", [superview subviews]);
1145 #endif
1146 }
1147
1148 bool wxWindow::DoPopupMenu(wxMenu *menu, int x, int y)
1149 {
1150     return false;
1151 }
1152
1153 // Get the window with the focus
1154 wxWindow *wxWindowBase::DoFindFocus()
1155 {
1156     // Basically we are somewhat emulating the responder chain here except
1157     // we are only loking for the first responder in the key window or
1158     // upon failing to find one if the main window is different we look
1159     // for the first responder in the main window.
1160
1161     // Note that the firstResponder doesn't necessarily have to be an
1162     // NSView but wxCocoaNSView::GetFromCocoa() will simply return
1163     // NULL unless it finds its argument in its hash map.
1164
1165     wxCocoaNSView *win;
1166
1167     NSWindow *keyWindow = [[NSApplication sharedApplication] keyWindow];
1168     win = wxCocoaNSView::GetFromCocoa(static_cast<NSView*>([keyWindow firstResponder]));
1169     if(win)
1170         return win->GetWxWindow();
1171
1172     NSWindow *mainWindow = [[NSApplication sharedApplication] keyWindow];
1173     if(mainWindow == keyWindow)
1174         return NULL;
1175     win = wxCocoaNSView::GetFromCocoa(static_cast<NSView*>([mainWindow firstResponder]));
1176     if(win)
1177         return win->GetWxWindow();
1178
1179     return NULL;
1180 }
1181
1182 /* static */ wxWindow *wxWindowBase::GetCapture()
1183 {
1184     // TODO
1185     return wxWindowCocoa::sm_capturedWindow;
1186 }
1187
1188 wxWindow *wxGetActiveWindow()
1189 {
1190     // TODO
1191     return NULL;
1192 }
1193
1194 wxPoint wxGetMousePosition()
1195 {
1196     // TODO
1197     return wxDefaultPosition;
1198 }
1199
1200 wxMouseState wxGetMouseState()
1201 {
1202     wxMouseState ms;
1203     // TODO
1204     return ms;
1205 }
1206
1207 wxWindow* wxFindWindowAtPointer(wxPoint& pt)
1208 {
1209     pt = wxGetMousePosition();
1210     return NULL;
1211 }
1212
1213
1214 // ========================================================================
1215 // wxCocoaTrackingRectManager
1216 // ========================================================================
1217
1218 wxCocoaTrackingRectManager::wxCocoaTrackingRectManager(wxWindow *window)
1219 :   m_window(window)
1220 {
1221     m_isTrackingRectActive = false;
1222     m_runLoopObserver = NULL;
1223     BuildTrackingRect();
1224 }
1225
1226 void wxCocoaTrackingRectManager::ClearTrackingRect()
1227 {
1228     if(m_isTrackingRectActive)
1229     {
1230         [m_window->GetNSView() removeTrackingRect:m_trackingRectTag];
1231         m_isTrackingRectActive = false;
1232     }
1233     // If we were doing periodic events we need to clear those too
1234     StopSynthesizingEvents();
1235 }
1236
1237 void wxCocoaTrackingRectManager::StopSynthesizingEvents()
1238 {
1239     if(m_runLoopObserver != NULL)
1240     {
1241         CFRunLoopRemoveObserver([[NSRunLoop currentRunLoop] getCFRunLoop], m_runLoopObserver, kCFRunLoopCommonModes);
1242         CFRelease(m_runLoopObserver);
1243         m_runLoopObserver = NULL;
1244     }
1245 }
1246
1247 void wxCocoaTrackingRectManager::BuildTrackingRect()
1248 {
1249     wxASSERT_MSG(!m_isTrackingRectActive, wxT("Tracking rect was not cleared"));
1250     if([m_window->GetNSView() window] != nil)
1251     {
1252         m_trackingRectTag = [m_window->GetNSView() addTrackingRect:[m_window->GetNSView() visibleRect] owner:m_window->GetNSView() userData:NULL assumeInside:NO];
1253         m_isTrackingRectActive = true;
1254     }
1255 }
1256
1257 static NSPoint s_lastScreenMouseLocation = NSZeroPoint;
1258
1259 static void SynthesizeMouseMovedEvent(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info)
1260 {
1261     NSPoint screenMouseLocation = [NSEvent mouseLocation];
1262     if(screenMouseLocation.x != s_lastScreenMouseLocation.x || screenMouseLocation.y != s_lastScreenMouseLocation.y)
1263     {
1264         wxCocoaNSView *win = reinterpret_cast<wxCocoaNSView*>(info);
1265         win->Cocoa_synthesizeMouseMoved();
1266     }
1267 }
1268
1269 void wxCocoaTrackingRectManager::BeginSynthesizingEvents()
1270 {
1271     CFRunLoopObserverContext observerContext =
1272     {   0
1273     ,   static_cast<wxCocoaNSView*>(m_window)
1274     ,   NULL
1275     ,   NULL
1276     ,   NULL
1277     };
1278     m_runLoopObserver = CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopBeforeWaiting, TRUE, 0, SynthesizeMouseMovedEvent, &observerContext);
1279     CFRunLoopAddObserver([[NSRunLoop currentRunLoop] getCFRunLoop], m_runLoopObserver, kCFRunLoopCommonModes);
1280 }
1281
1282 void wxCocoaTrackingRectManager::RebuildTrackingRect()
1283 {
1284     ClearTrackingRect();
1285     BuildTrackingRect();
1286 }
1287
1288 wxCocoaTrackingRectManager::~wxCocoaTrackingRectManager()
1289 {
1290     ClearTrackingRect();
1291 }
1292
1293 bool wxCocoaTrackingRectManager::IsOwnerOfEvent(NSEvent *anEvent)
1294 {
1295     return m_isTrackingRectActive && (m_trackingRectTag == [anEvent trackingNumber]);
1296 }
1297